I've got this code, but it doesn't seem to return true. The alert always shows up. Any thoughts (without needing to create a var in which to store that a checkbox has been selected as that just seems a bit hacky).
Thanks.
$("#form").submit(function(e) {
$('input[type=checkbox]').each(function () {
if(this.checked){
return true;
}
});
alert("Please select at least one to upgrade.");
return false;
});
You don't need to do the loop to determine if a checkbox is checked. The :checked selector filters out all that are not checked. Then you can use $.length to get a count of the checked inputs.
$("#form").submit(function(e) {
if(!$('input[type=checkbox]:checked').length) {
alert("Please select at least one to upgrade.");
//stop the form from submitting
return false;
}
return true;
});
Additionally, using your approach, a small change should make this work
$("#form").submit(function(e) {
$('input[type=checkbox]').each(function () {
if($(this).is(':checked')){
return true;
}
});
alert("Please select at least one to upgrade.");
return false;
});
I think you may be simply missing the $() around this
Just to point out, you're using the id reference #form. Did you mean to just refer to all forms, or does the form have the id form?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With