Reputation: 4660
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
Upvotes: 5
Views: 2636
Reputation: 78687
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;
}
Upvotes: 1
Reputation: 342765
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);
}
});
}
Upvotes: 4
Reputation: 26169
function doconfirm() {
if ($('select').each(function() {
if($(this).val() == '') {
alert("Please Select All Fields");
return(false);
}
});
}
Upvotes: 8