Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get all select elements that do not have an option selected using jQuery?

How do I get all select elements that do not have an option selected using jQuery?

<select id="one">
     <option value=""></option>
     <option value="test"></option>
</select>

<select id="two">
     <option value=""></option>
     <option selected value="test"></option>
</select>

What would the jQuery selector be that would return just #one based on no selection?

like image 458
Eric Packwood Avatar asked Aug 22 '16 21:08

Eric Packwood


3 Answers

Refer to https://stackoverflow.com/a/63588880/3499595 if your case is not similar to OP (default value is "")

$('select option:selected[value=""]').parent()
  • Selects all the :selected options of all the select elements
  • Checks if the selected option has a value of "", which in your case means no option is actually selected.
  • Returns the parent (which would be a select)
like image 65
yuriy636 Avatar answered Sep 21 '22 02:09

yuriy636


You can take advantage of jQuery's .parent() and .not() functions. See below:

// selector for all 'select' elements with any option below it
var all = $("select>option").parent(); // alternative $("select")

// selector for all 'select' element with a selected child
var selected = $("select>option[selected]").parent();

// the subtraction set "all - selected" achieved by `not`.
var unselected = all.not(selected);

Note that jQuery's parent takes care of removing duplicates from a set of parents of child elements.

JsFiddle here.

like image 40
EyasSH Avatar answered Sep 21 '22 02:09

EyasSH


The accepted answer gives all select elements with a selected option whose value is empty(""), which does answer the question in regard to the OP's sample HTML, where options with empty values are given, but it doesn't really answer the title question.

There is a difference between selecting an option with an empty value, and not selecting any option at all.

To select all select elements with no option selected, use

 $('select').not(':has(option:selected)')
like image 38
Aaron Dunigan AtLee Avatar answered Sep 18 '22 02:09

Aaron Dunigan AtLee