validation for at least one checkbox

后端 未结 1 389
不思量自难忘°
不思量自难忘° 2020-12-03 17:55

I have seen a couple of other posts with the same question but couldn\'t get the solution to work for me so I\'m posting my own question.

Let me preface this by sayi

1条回答
  •  一向
    一向 (楼主)
    2020-12-03 18:49

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

    Updated - 12 Jan 2015 => http://jsfiddle.net/r24kcvz6/ CDN was cahnged http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/jquery.validate.js - you can replicate the behaviour by deselcting all the checkboxes and clicking on the submit button.

    • http://jqueryvalidation.org/#latest-files-on-jsdelivr-cdn-%28hotlinking-welcome%29:

    code

    $.validator.addMethod('require-one', function(value) {
        return $('.require-one:checked').size() > 0;
    }, 'Please check at least one box.');
    
    var checkboxes = $('.require-one');
    var checkbox_names = $.map(checkboxes, function(e, i) {
        return $(e).attr("name")
    }).join(" ");
    
    $("#itemForm").validate({
        groups: {
            checks: checkbox_names
        },
        errorPlacement: function(error, element) {
            if (element.attr("type") == "checkbox") error.insertAfter(checkboxes.last());
            else error.insertAfter(element);
        }
    });
    

    html




    Image if you un-tick the validation will trigger

    enter image description here

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