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?
Refer to https://stackoverflow.com/a/63588880/3499595 if your case is not similar to OP (default value is "")
$('select option:selected[value=""]').parent()
:selected
options of all the select
elements""
, which in your case means no option is actually selected.select
)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.
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)')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With