如果使用jquery选择其中两个复选框,则禁用其他复选框

时间:2014-06-16 09:36:02

标签: javascript php jquery checkbox

我有4个以下的复选框。

<input type="checkbox" id="41" name="4[]" value="abc" style="width:10px"></td>
<input type="checkbox" id="42" name="4[]" value="qwe" style="width:10px"></td>
<input type="checkbox" id="43" name="4[]" value="xyz" style="width:10px"></td>
<input type="checkbox" id="44" name="4[]" value="pqr" style="width:10px"></td>

如果我选择其中两个复选框,我需要一种方法来禁用其他复选框。

非常感谢任何帮助。

5 个答案:

答案 0 :(得分:4)

您可以使用:

$(":checkbox[name='4[]']").change(function(){
  if ($(":checkbox[name='4[]']:checked").length == 2)                                              
   $(':checkbox:not(:checked)').prop('disabled', true);  
  else                                                     
   $(':checkbox:not(:checked)').prop('disabled', false); 
});

<强> Working Demo

答案 1 :(得分:1)

试试这个

$('input:checkbox').on('change', function(evt) {
   if($(this).siblings(':checked').length >= 2) {
       this.checked = false;
       console.log(this.value)
   }
});

DEMO

答案 2 :(得分:0)

试试这个。

  

的Javascript

$('input[type=checkbox]').change(function(){
    if($(this).is(':checked')){
$('input[type=checkbox]').attr('disabled',true);
    $(this).attr('disabled','');
}
else{
$('input[type=checkbox]').attr('disabled','');
}
});
  

HTML

1 <input type="checkbox" name="finallevelusers[]" value="1"/>
2 <input type="checkbox" name="finallevelusers[]" value="1"/>
3 <input type="checkbox" name="finallevelusers[]" value="1"/>
4 <input type="checkbox" name="finallevelusers[]" value="1"/>

Demo

答案 3 :(得分:0)

<强> Demo Fiddle

$('[type="checkbox"]').change(function(){

    if(this.checked && $(':checked').length == 2){
        $('[type="checkbox"]').not(':checked').prop('disabled',true);
    }
});
  • 为元素使用唯一的Id属性。

  • 如果没有公共属性,请使用通用选择器的公共类名称,例如$('[type="checkbox"]')

  • 使用$(':checked').length伪的
  • :checked,您只能找到已检查的输入。

  • .prop('disabled',true);用于停用输入 - 请参阅 .prop()

答案 4 :(得分:0)

首先开始为每个复选框添加唯一ID。 然后你可以附加功能来改变这样的事件:

$("input[type=checkbox]").change(function() {
...
});

然后简单地计算:检查项目并瞧瞧:

var n = $("input:checked").length;

休息,你可以自己做,我想。