Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select not Selected

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

like image 573
Tony Borf Avatar asked Jul 01 '09 18:07

Tony Borf


2 Answers


function doconfirm() {
  if ($('select').each(function() {
    if($(this).val() == '') {
         alert("Please Select All Fields");
         return(false);
    }  
  });
}
like image 185
Matthew Groves Avatar answered Oct 30 '22 09:10

Matthew Groves


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);
    }  
  });
}
like image 24
karim79 Avatar answered Oct 30 '22 08:10

karim79