views:

161

answers:

4

I have a form with 4 dropdowns on it. The default selected option in all the dropdowns is "Please Select". I want to use Jquery to make sure all dropdowns have a value before the page is submitted, but my code only works on the first one. Does anyone have a way that I can check all of the dropdowns at once?

function doconfirm() {
  if ($('select').val() == '') {
    alert("Please Select All Fields");
   }  
}

I'm sure I am missing something but I cant figure it out. Thanks

+8  A: 

function doconfirm() {
  if ($('select').each(function() {
    if($(this).val() == '') {
         alert("Please Select All Fields");
         return(false);
    }  
  });
}
mgroves
each is exactly what you need. http://docs.jquery.com/Core/each
Artem Russakovskii
And make sure that your html is correct -- <option value="">Please Select</option> and <option>Please Select</option> will return different things with val(). The first is an empty string, the second returns "Please Select"
artlung
Thanks that did it.
Tony Borf
A: 
$('select').each(function(s){if(!this.val())...});
Detect
+4  A: 

A slight variation on @mgroves' approach, this explicitly tests for at least one selected option, and alerts on the first select that doesn't have one. If there is any advantage to this approach, it is better readability (especially since the use of .val() is somewhat ambiguous for this purpose):

function doconfirm() {
  if($('select').each(function() {
    if(!$(this).find('option:selected').length) {
         alert("Please Select All Fields");
         return(false);
    }  
  });
}
karim79
+1  A: 

for a different take on this why not use

function doConfirm() {

    var toReturn = true;

    if ( $('select').filter( function(){
            return $(this).val() === ''; 
         }).length ) {

        toReturn = false;
        //notify user

    }

    return toReturn;
}
redsquare