Skip to content Skip to sidebar Skip to footer

Warn User If All Checkboxes Are Unchecked

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 t

Solution 1:

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")};
});

Solution 2:

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');
    }
});

Solution 3:

Try this:

My html:

<inputid="chkbx_0"type="checkbox"class="checkbox" name="c_n_0" checked="checked" />Option 1
<br/><inputid="chkbx_1"type="checkbox"class="checkbox" name="c_n_1" />Option 2
<br/><inputid="chkbx_2"type="checkbox"class="checkbox" name="c_n_2" />Option 3
<br/><inputid="chkbx_3"type="checkbox"class="checkbox" name="c_n_3" checked="checked" />Option 4
<br/><br/>
<inputtype="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

Solution 4:

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

Solution 5:

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")};

Post a Comment for "Warn User If All Checkboxes Are Unchecked"