warn user if all checkboxes are unchecked

后端 未结 5 1653
借酒劲吻你
借酒劲吻你 2021-02-09 00:04

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

相关标签:
5条回答
  • 2021-02-09 00:20

    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

    0 讨论(0)
  • if (legchecked.size() == 0){ alert("no riders")};
    
    0 讨论(0)
  • 2021-02-09 00:24

    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")};
    });
    
    0 讨论(0)
  • 2021-02-09 00:36

    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")};
    
    0 讨论(0)
  • 2021-02-09 00:45

    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');
        }
    });
    
    0 讨论(0)
提交回复
热议问题