jQuery check/uncheck checkbox

vicnumb Mar 12, 2013

Mar 12 2013 Published by under jQuery & JavaScript

Using groups of checkboxes in modern web programs is not a rare thing.
Groups of checkboxes are frequently used on group actions like selecting multiple options from a list then doing a operation over the selected list.
Check/uncheck operation is pretty simple over a small group of options: like selecting 3 checkboxes out of 3. But what if there is necessary to select between 50 or even more options? what if it is necessary to select all 50 checkboxes?

To make life easier we can use jQuery to solve this.

 

Your list of checkboxes that you are going to apply group check/uncheck

Let’s create a HTML list of options.

  <label for="checkall">Check/Uncheck All Checkboxes</label>
  <input type="checkbox" id="checkall">
 
  <div id="options">
    <input type="checkbox" name="ids[]" value="1">
    <input type="checkbox" name="ids[]" value="2">
    <input type="checkbox" name="ids[]" value="3">
    <input type="checkbox" name="ids[]" value="4">
    <input type="checkbox" name="ids[]" value="5">
  </div>

We have a list of checkboxes named ids[], additionally we have a checkbox with id checkall.

 

How jQuery check/uncheck all checkboxes work, theory

jQuery task is to find out if “checkall” checkbox is checked and check all checkboxes in the list or find out if “checkall” is unchecked and uncheck all checkboxes in the list.

Taking into consideration jQuery is based a lot on HTML selectors, we first detect the “checkall” checkbox click action.
As soon as clicked filter out all our checkboxes in “ids” list and check/uncheck them all according to “checkall” status.
Other languages programmers would try using if..then expression, by determining if “checkall” is checked or not, then do 2 separate actions for checked and unchecked status.
The right way is the following:
– detect if clicked “checkall”
– find out all “ids” checkboxes, in our case we used parent selector “options”
– check/uncheck them according to “checkall” status

 

Check/Uncheck all jQuery snippet

(function(){
  $('#checkall').click(function () {
    $('#options').find(':checkbox').attr('checked', this.checked);
  });
})();

Feel free to suggest your jQuery examples.

No responses yet

Leave a Reply