jQuery Validation at least one checkbox is selected

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

I have the following piece of html code for form checkboxes

5条回答
  •  庸人自扰
    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;
        }
    });
    

提交回复
热议问题