Select All Checkboxes

Everyone works with grids. A lot of times, these grids have checkboxes to allow the user to perform an action on multiple items in the grid. Here is a quick overview of handling checkboxes in a grid situation.

Firstly, we have a table of items and each row has a checkbox in the first column.

Col 1 Col 2 Col 3 Col 4 Col 4
Value 1 Value 2 Value 3 Value 4 Value 5
Value 1 Value 2 Value 3 Value 4 Value 5
Value 1 Value 2 Value 3 Value 4 Value 5

So that is our table. The checkbox in the header is the select all checkbox. Clicking on this will toggle all row checkboxes on or off. We capture the select all checkbox change event, then we cycle through all row checkboxes. As we cycle through, we set the checked attribute to be that of the select all checkbox.

$("#selectall").change(function () {
    $(".item").each(function () {
        $(this).attr("checked", $("#selectall").is(":checked"));
    });
});

It's a great way to approach this. The ATTR method uses a boolean value (True or False). Conveniently, the is(":checked") method also returns a Boolean. So we can chain the two together and switch state based on the value of each item.

But, what happens when we are selecting all the row checkboxes individually? When we check the last row item, we want to check the select all checkbox so that it's state is in line with all items.

$(".item").change(function () {
    $("#selectall").attr("checked", $('.item').length == $('.item:checked').length);
});

It's a similar approach. We check how many row item checkboxes there are, then check how many of them are checked. If they are the same, check the select all check box.

Til next time ...