JavaScript to select all or none of the checkboxes in a form


Here is a quick demo of the select all or none JavaScript function that automatically toggles all of your checkboxes in a given form.

Demo
My favorite programming/scripting language is:

Select All | None

JavaScript

Perl

PHP

C++


This is the plain HTML of the form:

1
2
3
4
5
6
7
8
<form name="theForm">
My favorite programming/scripting language is:<p>
Select <a href="javascript:selectToggle(true, 'theForm');">All</a> | <a href="javascript:selectToggle(false, 'theForm');">None</a><p>
<input type="checkbox" name="answers[]" value="javascript">JavaScript<p>
<input type="checkbox" name="answers[]" value="perl">Perl<p>
<input type="checkbox" name="answers[]" value="php">PHP<p>
<input type="checkbox" name="answers[]" value="c++">C++
</form>

There is nothing exciting about the HTML code except for line 3 where all the magic happens. There are 2 links in this line of code:

  • All - When the user clicks on this link, it will execute the selectToggle() JavaScript function and passes over 2 arguments: the value to set the checkboxes (true in this case) and the name of the form.
  • None - This link executes the selectToggle() JavaScript function and passes over the false value to uncheck the checkboxes and the name of the form.

Here is a peek at the selectToggle() JavaScript function:

1
2
3
4
5
6
7
8
9
10
11
function selectToggle(toggle, form) {
     var myForm = document.forms[form];
     for( var i=0; i < myForm.length; i++ ) { 
          if(toggle) {
               myForm.elements[i].checked = "checked";
          } 
          else {
               myForm.elements[i].checked = "";
          }
     }
}

This function basically loops through all of the inputs in the given form name that is passed over as an argument. Depending on the value of the toggle parameter, which can be true or false, each form element will checked or unchecked respectively.