问题
I'm using the below selector to get all the form inputs that are pre-populated with a value.
$('input[value!=""]');
This works great and so I thought I could apply the same logic to my select elements using the following selector, though it seems to be selecting all the select elements in Chrome.
$('select[value!=""]');
Below is an example of two types of selects on the form:
<select name="phone2_type" id="phone2_type">
<option value="">Select one:</option>
<option value="HOME">Home</option>
<option value="CELL">Cell</option>
<option value="BUSN">Business</option>
</select>
<select name="state" id="state">
<option value="">Select one:</option>
<option value="XX">Outside USA/Canada</option>
<option value="AL" selected="selected">Alabama</option>
<option value="AK">Alaska</option>
...
</select>
I'd like to select the second select since it has a value selected already with the select="selected"
回答1:
$('select').has('option[selected="selected"]')
will get the select element. jsFiddle example.
回答2:
value
is not an attribute of select
tag.
So you need to try:
var emptySelect = $('select').filter(function() {
return $.trim( $(this).val() ) == '';
});
回答3:
For select you need to use a special selector made available by JQuery: :selected
So
$('#state option:selected').val()
is the current selected value.
If you need the do something on the select elements themself you could do something like:
$('#select option:selected').parents('select').dosomething(...)
来源:https://stackoverflow.com/questions/14942597/jquery-selector-for-select-elements-with-empty-value-attributes