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. <form name="theForm">
    
  2. My favorite programming/scripting language is:<p>
    
  3. Select <a href="javascript:selectToggle(true, 'theForm');">All</a> | <a href="javascript:selectToggle(false, 'theForm');">None</a><p>
    
  4. <input type="checkbox" name="answers[]" value="javascript">JavaScript<p>
    
  5. <input type="checkbox" name="answers[]" value="perl">Perl<p>
    
  6. <input type="checkbox" name="answers[]" value="php">PHP<p>
    
  7. <input type="checkbox" name="answers[]" value="c++">C++
    
  8. </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. function selectToggle(toggle, form) {
  2.      var myForm = document.forms[form];
  3.      for( var i=0; i < myForm.length; i++ ) { 
  4.           if(toggle) {
  5.                myForm.elements[i].checked = "checked";
  6.           } 
  7.           else {
  8.                myForm.elements[i].checked = "";
  9.           }
  10.      }
  11. }

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.

Published by

Allen Liu

Building websites is a passion of mine. During the course of my work, I have created some snippets of code that I hope will prove useful to other developers.

5 thoughts on “JavaScript to select all or none of the checkboxes in a form”

  1. Thank you so much, onclick scripts are confusing, and most do not work, I as a coder can understand this one, and it work perfectly.

  2. This is a good script, all the others i had found check or uncheck by the name of the checkbox and not by the form name

Leave a Reply

Your email address will not be published. Required fields are marked *