Jquery 验证复选框组

Jquery 验证复选框组,jquery,validation,checkbox,Jquery,Validation,Checkbox,我有几组复选框。每个组都包含在字段集中的一个div中 div应用了类chk_div。我希望能够将用户可以选择的复选框数量限制为3个。我有一个函数可以做到这一点,如果我给每个复选框一个唯一的ID并引用它,它就会工作 不过,我希望能够通过chk_div类完成这项工作。因此,我可以有任意多组复选框,只需执行一次jQuery 以下是为每个复选框使用唯一id的代码。-容器将是一个div id function CheckboxCount(container,maximum) {//Counts all t

我有几组复选框。每个组都包含在字段集中的一个div中

div应用了类chk_div。我希望能够将用户可以选择的复选框数量限制为3个。我有一个函数可以做到这一点,如果我给每个复选框一个唯一的ID并引用它,它就会工作

不过,我希望能够通过chk_div类完成这项工作。因此,我可以有任意多组复选框,只需执行一次jQuery

以下是为每个复选框使用唯一id的代码。-容器将是一个div id

function CheckboxCount(container,maximum)
{//Counts all the checked checkboxes in the given container and once the maximum number of boxes are checked it disables all the rest

    var Checked = ($(container +' :checkbox:checked').length); //Get the number of checkboxes in this container that are checked

    //If the maximum number of checkboxes in the given container have been checked we disable the unchecked ones until the number of checked is lower than max
    if (Checked >= maximum){$(container +' :checkbox:not(:checked)').attr("disabled",true);} //Disable all non checked check boxes
    else{$(container +' :checkbox').attr("disabled",false);} //Enable all checkboxes
}
此功能由以下代码触发:

$('#group1').click(function(){CheckboxCount('#group1',3);});
$('#group2').click(function(){CheckboxCount('#group2',3);});
其中group1、group2是包含复选框的div的id

我想要的是更像这样的东西

function test(container,maximum)
{
    $(container +' :checkbox').click(function(){

    var Checked = ($(container+' :checkbox:checked').length);

    if (Checked >= maximum){$(container +' :checkbox:not(:checked)').prop("disabled",true);} 
    else{$(container +' :checkbox').prop("disabled",false);} //Enable all checkboxes}

    });
}
容器是一个类,如您所见。click事件处理程序位于函数内部。唯一的问题是,无论复选框属于哪个组,它都适用于所有组

因此,如果我单击第一组中的三个复选框,它也会禁用第二组中的复选框


这是JSFIDLE,让你明白我的意思

我将把它简化为这个

$('.chk_div input').click(function() {
    if ($(this).parents('.chk_div').find('input:checked').length >= 3) {
        $(this).parents('.chk_div').find(':checkbox:not(:checked)').prop("disabled", true);
    }
    else {
        $(this).parents('.chk_div').find(':checkbox').prop("disabled", false);
    }
});​
将此选项与.closest()和.find()一起使用,以保持事件相对于要修改的复选框组


这似乎正是我想要的。谢谢你的快速回复!
$(container +' :checkbox').click(function() {

     var Checked = ($(this).closest(container).find('input:checked').length);

    if (Checked >= maximum) {
        $(this).closest(container).find('input:not(:checked)').prop("disabled",true);
    } 
    else {
        $(this).closest(container).find('input:checkbox').prop("disabled",false);
    } //Enable all checkboxes}

});