I have selects which all have a top option with text "All" and no value, but I need to write some code that works on all other options in these selects.
I have code as follow that works, but I'd rather do away with the conditional on the second line. I did try using jQuery's ':not' selector but couldn't figure out how to configure it for missing/null/undefined value. Would it best if I explicitly set value to the empty string "" and then use :not?
_.each($(select).find('option'), function(option) {
if (optionVal = $(option).val()) {
Please excuse my usage of _.each instead of jQuery's each, we'd rather stay consistent as we use underscore for lots more than just iterating over jQuery matched sets.
I have selects which all have a top option with text "All" and no value, but I need to write some code that works on all other options in these selects.
I have code as follow that works, but I'd rather do away with the conditional on the second line. I did try using jQuery's ':not' selector but couldn't figure out how to configure it for missing/null/undefined value. Would it best if I explicitly set value to the empty string "" and then use :not?
_.each($(select).find('option'), function(option) {
if (optionVal = $(option).val()) {
Please excuse my usage of _.each instead of jQuery's each, we'd rather stay consistent as we use underscore for lots more than just iterating over jQuery matched sets.
Share Improve this question asked Sep 13, 2013 at 18:21 DexygenDexygen 12.6k13 gold badges86 silver badges151 bronze badges4 Answers
Reset to default 6Off the top of my head, you could use either:
$(select).find('option[value!=""]');
or
$(select).find('option:not([value=""])');
to return the options that are not <option value="">All</option>
If the first option
is always the valueless option, you could also use:
$(select).find('option:not(:eq(0))')
to select all option
elements that are not the first-child
.
If you want to exclude the first Option from every Select element, you can use :not()
selector and .find()
method:
$('select').find('option:not(:first)');
In case that you want to filter the Options that have value, you can use .filter()
method:
$('select option').filter(function() {
return $.trim(this.value).length;
});
Note for iterating through jQuery collections it's better to use jQuery's .each()
method, otherwise you will lose the chainabilty that jQuery provides.
You may try this
HTML:
<select>
<option>All</option>
<option value>0</option>
<option value=1>One</option>
<option value=2>Two</option>
</select>
JS: This will return only last two options (One and Two)
$('select option').filter(function(){
return this.hasAttribute('value') && this.value.length;
});
to filter the options for missing/null/undefined
value. Here is an example.
$(select).find('option[value]'); // selects all <option>s with value
If I unserstood the question correctly.