jquery - best way of finding if select box option is unselected
Whats the best way to check a select box to find out if the selected options value is empty?
i have tried the following and other variations but no luck so far:
if($('.mySelectBox').val('').length) { alert('not selected');开发者_StackOverflow中文版 }
I think this is what you're looking for:
if(!$('.mySelectBox').val()) {
alert('not selected');
}
This alerts if the selected option has an empty value, e.g.:
<option value="">Please Select</option>
A suggestion though, if the box is unique, use an ID (this only checks the first class="mySelectBox"
, you'll need a loop if you want to check more than one).
if ($('.mySelectBox :selected').size() == 0) {
alert('not selected');
}
This selects the set of options in .mySelectBox
that are selected, and counts them.
Here's a live demo: http://jsfiddle.net/RTecb/
You are calling val
with an argument, that means it tries to set the value instead of getting the value. Try this instead:
if ($('.mySelectBox').val()) { alert('not selected'); }
精彩评论