简体   繁体   English

如何禁用所有未选中的复选框?

[英]How to disable all not checked checkbox?

In the html file there is a lot of checkbox element.在 html 文件中有很多复选框元素。 If 3 of them are checked, then the rest should be disabled, until one of the checked checkbox are again unchecked.如果选中其中 3 个,则应禁用 rest,直到再次取消选中选中的复选框之一。 Here is the JS code and HTML这是JS代码和HTML

 $('.check [type=checkbox]').change(function(){ var checkNum = $('.check [type=checkbox]'); var checkedNum = $('.check [type=checkbox]:checked').length; if(checkedNum >= 3){ for(i=0;i<checkNum.length; i++){ if(checkNum[i].prop('checked')==false){ (checkNum[i].prop('disabled')==true)) } } } })
 <label class="check"> <input type="checkbox"> <div>Select</div> </label> <label class="check"> <input type="checkbox"> <div>Select</div> </label> <label class="check"> <input type="checkbox"> <div>Select</div> </label> <label class="check"> <input type="checkbox"> <div>Select</div> </label>

You do not need any loop here.您在这里不需要任何循环。 If the condition is true then you can simply target the not checked check boxes to set the disabled attribute to true.如果条件为true ,那么您可以简单地针对未checked的复选框将disabled属性设置为真。 If the condition is false then set the attribute to false to all the check boxes:如果条件为false ,则将所有复选框的属性设置为false

 $('.check [type=checkbox]').change(function(){ var checkNum = $('.check [type=checkbox]'); var checkedNum = $('.check [type=checkbox]:checked'); if(checkedNum.length >= 3){ $('.check [type=checkbox]:not(:checked)').attr('disabled',true); } else{ checkNum.attr('disabled',false); } })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <label class="check"> <input type="checkbox"> <div>Select</div> </label> <label class="check"> <input type="checkbox"> <div>Select</div> </label> <label class="check"> <input type="checkbox"> <div>Select</div> </label> <label class="check"> <input type="checkbox"> <div>Select</div> </label>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM