In the html file there is a lot of checkbox element. If 3 of them are checked, then the rest should be disabled, until one of the checked checkbox are again unchecked. Here is the JS code and 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. If the condition is false
then set the attribute to false
to all the check boxes:
$('.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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.