Disable all checkboxes

the following code works fine but 1 error

$(document).ready(
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)
            .find(':checked')
            .attr('disabled',false)
    } else {
        $("#myCheckboxes input[type='checkbox']").attr('disabled',false);
    }


    });
 });

      

after selection becomes 4, all checkboxes become disabled even selected, but I don't want to disable the selected checkbox.

thank

+2


source to share


3 answers


try it

$("#myCheckboxes :checkbox:not(:checked)").attr('disabled', true)

      



instead

$("#myCheckboxes input[type='checkbox']")
    .attr('disabled',true)
    .find(':checked')
    .attr('disabled',false)

      

+11


source


You should note that this is not a way to enable / disable DOM elements.
Consider:

<input type="checkbox" disabled='true' />
<input type="checkbox" disabled='false' />

      

Contrary to what it looks like, since they have an attribute disabled

, both controls are disabled!
This is for back-compatibly where HTML is <input type="checkbox" disabled />

- the value is ignored.

Usually, to disable an element, use



<input type="checkbox" disabled='disabled' />

      

So the correct way to do it with jQuery is:

$("input:checkbox").attr('disabled', 'disabled'); //disable
$("input:checkbox").removeAttr('disabled'); //enable

      

+3


source


I have already adjusted my answer to your original question (which you strangely posted as another question on SO). I had a small typo that has since been corrected after your comment: set the total number of checkboxes in an array

0


source







All Articles