Page 1 of 1

All checkboxes except #id

Posted: Fri Jan 20, 2012 3:25 pm
by Celauran
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);
            }
        }
        
    });
});

Re: All checkboxes except #id

Posted: Fri Jan 20, 2012 6:41 pm
by Tiancris
I have an idea :idea:
Use a variable to count the number of checkboxes selected. When that number equals the total then you must select the checkbox "checkAll." The counter is changed each time you select / unselect a checkbox.
Something like this:

Code: Select all

$(document).ready(function() {
    var checkTotal = $(':checkbox').length;
    var checkedCount = 0;
    $('#checkAll').change(function() {
        $(':checkbox').prop('checked', $(this).prop('checked'));
        if ($(this).prop('checked')) {
          checkedCount = checkTotal;
        } else {
          checkedCount = 0;
        }
    });
    $(':checkbox').not('#checkAll').change(function() {
        if ($(this).prop('checked') == false)
        {
            $('#checkAll').prop('checked', false);
            checkedCount--;
        }
        else
        {
            checkedCount++;
            if (checkedCount == checkTotal)
            {
                $('#checkAll').prop('checked', true);
            }
        }
       
    });
});