jQuery: Select all checkboxes behavior

This behavior is useful when you have a group of checkboxes and you want to have an easy way to select or deselect them all, so you provide a “select all” checkbox.

It functions like this:

  • Checking the “select all” checkbox will cause all checkboxes to be checked.
  • Unchecking the “select all” checkbox will cause all checkboxes to be unchecked.
  • If manually checking all checkboxes, the “select all” checkbox should be automatically checked.
  • If all checkboxes are checked and one checkbox is manually unchecked, the “select all” checkbox should be automatically unchecked.

This behavior is very easy to replicate with jQuery:

var $selectAll = $(".selectAll"),
 $checkboxes = $("input:checkbox");

$selectAll.change(function () {
 $checkboxes.prop(
  "checked",
  $selectAll.prop("checked"));
});
$checkboxes.change(function () {
 $selectAll.prop(
  "checked",
  ($checkboxes.length === $checkboxes.filter(":checked").length));
});

But if you have to do this many times or if you have a more advanced use case, I recommend a better solution.

The jQuery Select All Checkboxes Plugin

The jQuery Select All Checkboxes Plugin handles all this behavior automatically.

The plugin has several alternative usages:

// apply select all behavior and target all checkboxes
$(".selectAll").selectAll();

// target specific checkboxes
$(".selectAll").selectAll(".checkbox");

// call on parent container
$(".container").selectAll({
    container: true,            // specify that we are using it on a container
    selectAll: ".selectAll",    // the "select all" checkbox selector string
    checkbox: ".checkbox"       // optionally target specific checkboxes
});

The container method has the advantage that it will listen to dynamic DOM changes, so if you are adding checkboxes dynamically to the page it is the way to go.

Visit the GitHub repository for more information and to obtain the source code.

Nuno Freitas
Posted by Nuno Freitas on August 31, 2015

Related articles