开发者

jquery - best way of finding if select box option is unselected

开发者 https://www.devze.com 2023-01-14 01:24 出处:网络
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:

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'); }
0

精彩评论

暂无评论...
验证码 换一张
取 消