Hazard Hazard - 5 months ago 18
HTML Question

How to select all/unselect all the check boxes which are not disabled?

I've multiple checkbox inputs while some them are disabled. So when I click select all/unselect all the checkbox at the top, I want to apply this event for the only enabled check boxes. Also when I've all the checkboxes checked by clicking on each one, then the select all checkbox must be clicked.

Note : Also I've one functionality, when the enabled checkbox is clicked and followed by the save click, then that particular checkbox will be disabled.I can add a new checkbox using add new checkbox button. When a new checkbox is added the select all/unselect all checkbox must be unchecked.

HTML

<input type="checkbox" id="ckbCheckAll" /><span>Select all</span>
<table id="myTable">
<tr>
<td>
<input type="checkbox" class="checkBoxClass" disabled="disabled" checked/> <span>Option1</span></td>
</tr>
<tr>
<td>
<input type="checkbox" class="checkBoxClass" /> <span>Option2</span></td>
</tr>
<tr>
<td>
<input type="checkbox" class="checkBoxClass" /> <span>Option3</span></td>
</tr>
<tr>
<td>
<input type="checkbox" class="checkBoxClass" /> <span>Option4</span></td>
</tr>
<tr>
<td>
<input type="checkbox" class="checkBoxClass" /> <span>Option5</span></td>
</tr>
</table>
<button id="add">
Add check box
</button>
<button id="save">
Save
</button>


JQuery

$(document).ready(function() {
$("#ckbCheckAll").click(function() {
$(".checkBoxClass").prop('checked', $(this).prop('checked'));
});
});
$(document).ready(function() {
$('.checkBoxClass').click(function() {
var selected = $('.checkBoxClass').length;
if ($('.checkBoxClass:checked:enabled').length === selected) {
$('#ckbCheckAll').prop('checked', true);
} else {
$('#ckbCheckAll').prop('checked', false);
}
})
});
$(document).ready(function() {
count = 5;
$('#save').click(function() {
$('.checkBoxClass').each(function() {
if ($(this).is(':checked')) {
$(this).prop('disabled', true);
}
})
});
$('#add').click(function() {
count = count + 1;
$('#myTable').append('<tr><td><input type="checkbox" class="checkBoxClass" /> <span>Option'+count+'</span></td></tr>')
});
})


Fiddle

hsh hsh
Answer

To detect disabled check boxes you can use jquery filter method like this:

$(".checkBoxClass").filter(function(){
    return !$(this).attr('disabled');
}).prop('checked', $(this).prop('checked'));

by using filter like this, JQuery changes checkboxes that have not disabled attribute.

and use .prop('checked', false) or .attr('checked', false) to uncheck checkboxes on add new checkbox button.

so to uncheck select all on save and add checkbox use:

$("#ckbCheckAll").attr('checked', false);

and to uncheck all enabled checkboxes on addcheckbox use:

$(".checkBoxClass").filter(function(){
    return !$(this).attr('disabled');
}).prop('checked', false);

Updated Fiddle