All checkboxes except #id
Posted: Fri Jan 20, 2012 3:25 pm
I have a table containing a list of users. Each row has a checkbox with that user's ID as its value. I have added a checkbox #checkAll at the top of the table to toggle all checkboxes. As soon as one checkbox is unchecked, #checkAll is also unchecked. Where I ran into trouble was doing the opposite; if the user manually checked all the boxes (except #checkAll), I want #checkAll to be checked. I've managed using the code below, but there must be a better/more elegant way. Thanks for any suggestions.
Code: Select all
$(document).ready(function() {
$('#checkAll').change(function() {
$(':checkbox').prop('checked', $(this).prop('checked'));
});
$(':checkbox').not('#checkAll').change(function() {
if ($(this).prop('checked') == false)
{
$('#checkAll').prop('checked', false);
}
else
{
// This is the kludge I'd like to improve
var all = true;
$(':checkbox').not('#checkAll').each(function() {
if ($(this).prop('checked') == false)
{
all = false;
}
});
if (all == true)
{
$('#checkAll').prop('checked', true);
}
}
});
});