I have a form with a series of checkboxes. I want to warn the user, after they hit submit, if ALL of the checkboxes are unchecked. I'm using the following code to report all of the values of the checkboxes:
$('[id^=leg_rider]').filter(':checked');
This seems to work. However, when I try to check to see if the returned object is empty, it doesn't seem to work. This is what I'm trying:
$("#set_pref_submit").click(function() {
var legchecked = $('[id^=leg_rider]').filter(':checked');
if (!legchecked){ alert("no riders")};
});
Any suggestions are appreciated. Thanks!
To check if all checkboxes are unchecked with JavaScript, we can select all the checked checkboxes with document. querySelector . to add a form with some checkboxes. to select all the checked checkboxes with document.
type == 'checkbox' && inputs[x]. name == 'us') { is_checked = inputs[x]. checked; if(is_checked) break; } } // is_checked will be boolean 'true' if any are checked at this point.
So the correct code is: $('input. abc'). not(':checked'). length === 0 .
You can use jQuery object's length
property:
$("#set_pref_submit").click(function() {
var legchecked = $('input[id^=leg_rider]:checked').length;
if (legchecked){ alert("no riders")};
});
Working Demo : http://jsfiddle.net/MrkfW/
Try this: using .change api as well so it keep the track :)
API: http://api.jquery.com/change/
$("input[type='checkbox'][id^=leg_rider]").change(function(){
var a = $("input[type='checkbox'][id^=leg_rider]");
if(a.length == a.filter(":checked").length){
alert('all checked');
} else {
alert('not all checked');
}
});
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