2012-12-21 71 views
3

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

该div有类chk_div应用于它。我希望能够限制用户可以选择的复选框的数量3.我有一个这样做的功能,它可以工作,如果我给每个复选框一个唯一的ID并引用它。

但是我希望能够通过chk_div类来完成。所以我可以拥有任意数量的复选框,而且只需要执行一次jQuery。

下面是每个复选框使用唯一标识的代码。 - 容器将是一个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);}); 

其中1组触发的,第2组是包含复选框的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} 

    }); 
} 

当容器是一个类,你可以看到的。点击事件处理进入里面的功能。唯一的问题是,无论复选框属于哪个组,它都适用于所有组。

所以,如果我在一个组中,单击三个复选框,还会禁用第2组

这里的的jsfiddle所以你可以明白我的意思。 - http://jsfiddle.net/jSgp9/

回答

3

我会简化它到这个jsFiddle example

$('.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); 
    } 
});​ 
+1

这似乎是我想要的。感谢您的快速回复! –

1

使用.closest().find()保持相对于正在修改的复选框组事件。

http://jsfiddle.net/jSgp9/12/

$(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} 

});