Warn user if all checkboxes are unchecked

I have a form with a series of checkboxes. I want to warn the user after they click submit if ALL the boxes are unchecked. I use the following code to report all flag values:

$('[id^=leg_rider]').filter(':checked');

It seems to work. However, when I try to check if the object returned is not working. This is what I am trying:

        $("#set_pref_submit").click(function() {
        var legchecked = $('[id^=leg_rider]').filter(':checked');
        if (!legchecked){ alert("no riders")};
    });

Any suggestions are welcome. Thank!

+5
source share
5 answers

You can use the jQuery object lengthproperty:

$("#set_pref_submit").click(function() {
    var legchecked = $('input[id^=leg_rider]:checked').length;
    if (legchecked){ alert("no riders")};
});
+10
source

Working demo : http://jsfiddle.net/MrkfW/

Try this: using .change api to save 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');
    }
});
+5

:

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"/>​

JQuery:

jQuery(".testall").click(function () {
    if (jQuery(".checkbox:checked").length == 0) { alert("no riders"); }
});

: http://jsfiddle.net/webwarrior/NJwv4/9/

This will give you the opportunity to check only certain flags.

hth, shaun

+2
source
if (legchecked.size() == 0){ alert("no riders")};
0
source

In line

if (!legchecked){ alert("no riders")};

In fact, you are checking for the existence of an object, not an empty one. Since you are using jQuery, you can use the .isEmptyObject () function to check if the object is empty.

if($.isEmptyObject(legchecked)) {alert ("no riders")};
0
source

All Articles