development blog.

jQuery Check All Checkbox

by John Pasquet Wednesday, August 17th, 2011

The Problem

Create a “select all” checkbox that

  1. when checked or unchecked, applies its value to all the checkboxes defined as its children
  2. when a child checkbox is checked or unchecked, the “select all” checkbox is updated accordingly.  So, if you click the “select all”, but then uncheck one child checbox, deselect the “select all” checkbox.

The Solution


initSelectAll: function ($chkAll, $checkboxes) {

    //when chkAll is clicked, update the other checkboxes with its value
    $chkAll.click(function () {
        $checkboxes.attr("checked", $chkAll.attr("checked"));
    });

    // when any child checkbox is checked or unchecked reset the chkAll value
    // chkAll will be checked if number of checked checkboxes = total number of checkboxes.
    $checkboxes.click(function () {
        $chkAll.attr("checked", $checkboxes.filter(":checked").length == $checkboxes.length);
    }
}

$chkAll = $("#chkAll"); // or however you select the select all checkbox
$checkboxes = $("#checkboxes :checkbox");

$(function () {
    initSelectAll($chkAll, $checkboxes);
});

Tags: , ,

« »

One Response to “jQuery Check All Checkbox”

  1. Foliotek Development Blog » Blog Archive » Datagrid Checkbox Column Says:

    [...] the select/deselect all functionality. See this blog post in reference to the :asp() selector, and this post for more information on the select all functionality. Note: we’re not using selectAllInTable [...]

Leave a Reply

NoFollow Plugin made by Web Hosting