jQuery Validation at least one checkbox is selected

后端 未结 5 1699
鱼传尺愫
鱼传尺愫 2021-01-15 02:05

I have the following piece of html code for form checkboxes

相关标签:
5条回答
  • 2021-01-15 02:45

    This is very simple......

    function validate_form()
    {
    valid = true;
    
    if($('input[type=checkbox]:checked').length == 0)
    {
        alert ( "ERROR! Please select at least one checkbox" );
        valid = false;
    }
    
    return valid;
    }
    

    HTML

    <form name="myform" method="post" action="#" onsubmit="return validate_form();">
    <input type="checkbox" name="box1"  value="box1">Box1
    <input type="checkbox" name="box2"  value="box2">Box2
    <input name="submit" type="submit" value="Submit"/>
    </form>
    
    0 讨论(0)
  • 2021-01-15 02:46

    Try with this

    $("#YourbuttonId").click(function(){
        if($('input[type=checkbox]:checked').length == 0)
        {
            alert('Please select atleast one checkbox');
        }
    });
    

    By Plugin

    HTML

    <label class="checkbox inline">
    <input type="checkbox" id="typecb1" name="spamm[]" value="Loading Point"> Loading Point
    </label>
    <label class="checkbox inline">
    <input type="checkbox" id="typecb2" name="spamm[]" value="Unloading Point"> Unloading Point
    </label>
    <label class="checkbox">
    <input type="checkbox" id="typecb3" name="spamm[]" value="Retailer Unloading"> Retailer Unloading
    </label>
    

    Script

    rules:{
         "spamm[]": { 
          required: true, 
          minlength: 1 
          }
       }
    
    0 讨论(0)
  • 2021-01-15 02:50

    Quote OP:

    "I want to make sure that at least one of the check boxes is selected."

    If you want to use the jQuery Validate plugin, and all checkboxes have a different name, simply use the require_from_group method that's part of the additional-methods.js file.

    Since you already have a common class on these checkboxes called require-one, it's even easier.

    $('#form').validate({
        rules: {
            fieldname: {
                require_from_group: [1, '.require-one']
            },
            // declare same rule on all eight checkboxes
            ....
            ....
        }
    });
    

    However, rather than declare all eight of these within .validate(), you can use the .rules('add') method inside of a jQuery .each() to declare them all at once.

    $('.require-one').each(function () {
        $(this).rules('add', {
            require_from_group: [1, this],
            messages: {
                require_from_group: "please check one"
            }
        });
    });
    

    Then to combine all eight messages into one, use the groups option...

    $('#form').validate({
        groups: {  // combine these error messages into one
            checkboxes: 'allwines beer redwines cider whitewines spirits sparkling fortified'
        }
    });
    

    Working DEMO: http://jsfiddle.net/JVWu2/1/

    Placing your error message into the #error_msg3 error box is no different than placing any of your other jQuery Validate messages.

    0 讨论(0)
  • 2021-01-15 02:50

    Try

    adding this code will do

    var chck = $('input[type=checkbox]');
    chck.addClass('check-one');
    $.validator.addMethod('check-one', function (value) {
        return (chck.filter(':checked').length > 0);
    }, 'Check at least one checkbox');
    


    fiddle Demo

    Group will show error in front first check-box only

    var chck = $('input[type=checkbox]');
    chck.addClass('check-one');
    $.validator.addMethod('check-one', function (value) {
        return (chck.filter(':checked').length > 0);
    }, 'Check at least one checkbox');
    var chk_names = $.map(chck, function (el, i) {
        return $(el).prop("name");
    }).join(" ");
    $("#submitDetails").validate({
        groups: {
            checks: chk_names
        },
        submitHandler: function (form) {
            alert('Form Submited');
            return false;
        }
    });
    


    Remove group if you want error to show in front of all check-boxes

    fiddle Demo

    $("#submitDetails").validate({
        submitHandler: function (form) {
            alert('Form Submited');
            return false;
        }
    });
    
    0 讨论(0)
  • 2021-01-15 03:02

    You will have to change the name attributes of the checkboxes, and add a rule for it with the minlength set to 1.

    You can after show the custom message and append it to #error_msg3 with :

    if(element.attr("name") == "check") error.appendTo("#error_msg3")
    

    EDIT

    $("input[type='checkbox'][name='check']").change(function() {
        if ($("input[type='checkbox'][name='check']:checked").length){
            $(this).valid()
        }
    })
    

    EDIT 2

    I've updated the Fiddle, now the message toggles correctly when you have at least one checkbox checked or not.

    $("input[type='checkbox'][name='check']").change(function() {
        $('#submitDetails').valid();
    });
    


    Fiddle here

    0 讨论(0)
提交回复
热议问题