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!
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');
}
});
Try this:
My html:
<input id="chkbx_0" type="checkbox" class="checkbox" name="c_n_0" checked="checked" />Option 1
<br/><input id="chkbx_1" type="checkbox" class="checkbox" name="c_n_1" />Option 2
<br/><input id="chkbx_2" type="checkbox" class="checkbox" name="c_n_2" />Option 3
<br/><input id="chkbx_3" type="checkbox" class="checkbox" name="c_n_3" checked="checked" />Option 4
<br/><br/>
<input type="button" value="Click me" class="testall"/>
My JQuery Code:
jQuery(".testall").click(function () {
if (jQuery(".checkbox:checked").length == 0) { alert("no riders"); }
});
Live example:
http://jsfiddle.net/webwarrior/NJwv4/9/
This will give you the option to check only certain checkboxes.
hth, Shaun
if (legchecked.size() == 0){ alert("no riders")};
On the line
if (!legchecked){ alert("no riders")};
You're actually checking the existence of the object, not if it's empty. Since you're using jQuery, you could use the .isEmptyObject() function to check if the object is empty.
if($.isEmptyObject(legchecked)) {alert ("no riders")};