The Netlobo logo - a Nevada desert landscape

Checkbox Magic - Checking, Unchecking, and Inverting with Javascript

How to check/uncheck/invert the checkboxes in a form using Javascript.

Published Mar 31, 2006 by lobo235
Last updated on May 19, 2009

Dealing with HTML forms can be a pain at times but javascript can help to ease that pain. Dealing with large groups of checkboxes in a form can be frustrating for visitors especially when they want to check all of the checkboxes and they have to click them one by one. Here are some javascript functions that I wrote to make your job easier as a webmaster and to make your forms easier to use for your visitors.

Please feel free to use these functions wherever you wish. Please give credit where credit is due.

/***************************************************
 * www.netlobo.com
 * Checkbox checking/unchecking/inverting functions
 *
 * Pass the id of the form into the function and
 * all the checkboxes in that form will be
 * checked/unchecked/inverted.
 *
 * This example checks all the checkboxes in the
 * form with the id 'survey':
 * checkAll('survey');
 **************************************************/

function checkAll(id){
   var f = document.getElementById(id);
   var inputs = f.getElementsByTagName("input");
   for(var t = 0;t < inputs.length;t++){
     if(inputs[t].type == "checkbox")
       inputs[t].checked = true;
   }
 }
 function uncheckAll(id){
   var f = document.getElementById(id);
   var inputs = f.getElementsByTagName("input");
   for(var t = 0;t < inputs.length;t++){
     if(inputs[t].type == "checkbox")
       inputs[t].checked = false;
   }
 }
 function invertAll(id){
   var f = document.getElementById(id);
   var inputs = f.getElementsByTagName("input");
   for(var t = 0;t < inputs.length;t++){
     if(inputs[t].type == "checkbox")
       inputs[t].checked = !inputs[t].checked;
   }
 }

The first two functions are fairly straightforward. They either check or uncheck all of the checkboxes in the form with the given id. The third function is not seen as often as the other two. It will invert all of the checkboxes in the form, or in other words, it will check all of the unchecked checkboxes and uncheck all of the checked checkboxes. This can be useful when the visitor has mistakenly checked all the options they didn't want when they were actually supposed to check all the options they did want. They can quickly change all of their choices without having to spend a whole lot of time doing it.

You can download the .js file here: nlb_formcheck.js

You can see an example of these functions in use here: Form Check Example

0 comments for this article.

del.icio.us logo add this article to del.icio.us! Other great Web Development and Programming articles on Netlobo.com:
Managing Multiple Javascript window.onload Functions
Preventing MySQL Injection attacks with PHP
Persistent Login Cookies Done Right