tags:

views:

34

answers:

3

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'); }
+1  A: 
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/

Ender
The first option will be selected, so this really doesn't work :)
Nick Craver
Depends on whether this is a dropdown or a select box, but good point :)
Ender
+2  A: 

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).

Nick Craver
A: 

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