设置数组中复选框的总数

我有像这样的复选框数组

for($j=1;$j<=10;$j++) <input type="checkbox" name="chkLimit[]" id="chkLimit_" value="" /> 

我有10个复选框

我写这样的jquery代码……

  $(document).ready( function (){ setLimitSelection(); } ); function setLimitSelection(){ $('input[name="chkLimit[]"]').limitSelection( { // number of items to limit to limit: 4, // on error, do this onfailure: function (n){ $("#idCheckboxMsg").html( "You can not select more than " + n + " items." ); return false; }, // on success, do this onsuccess: function (n){ $("#idCheckboxMsg").html(""); return false; } } ); $('select[name="selLimit[]"]').limitSelection(10); } $("input.chkLimit").click(function() { var numSelected = $("input.chkLimit[]:checked").length; var numLeft = 10 - parseInt(numSelected); $("#statusBox").html("You have "+numSelected+" CD's selected.
You have "+numLeft+" selections left."); });

我想要的是:用户不能选择超过4个复选框

谢谢

我没有对此进行测试,但它应该为您完成工作:

 $(function(){ $("#myCheckboxes input[type='checkbox']").change( var checked = $("#myCheckboxes input[type='checkbox'][checked]").length; if(checked == 4){ $("#myCheckboxes input[@type='checkbox']").not(":checked").attr('disabled',true); }else{ $("#myCheckboxes input[@type='checkbox']").not(":checked").attr('disabled',false); } ) }); 

每次复选框的选中状态发生变化时,它会查看复选的复选框数。 如果有4,则禁用未选中的框,否则启用它们。 这假设它们都存在于一个名为#myCheckboxes的容器中

看起来@inkedmn有一些语法错误,但评论框不足以详细说明。 所以,这就是我认为他正在尝试做的事情:

 $(function(){ $("#myCheckboxes input[type='checkbox']").change(function() { var checked = $("#myCheckboxes input[type='checkbox']:checked").length; if(checked == 4){ $("#myCheckboxes input[type='checkbox']") .attr('disabled',true) .filter(':not(:checked)') .attr('disabled',false); } else { $("#myCheckboxes input[type='checkbox']").attr('disabled',false); } ) }); 

那应该为你完成。