W3hobbyist

Snippets and resources for PHP, MySQL, JavaScript-AJAX

Fastest and easiest way to invert checkbox selection using javascript

without comments

Inverting checkbox selection seems a fairly common task needed with forms. While there are many already available, if you go through the below code, you can yourself tell the difference between this and other ones.

<!-- part of the HTML form-->
   <fieldset id="all_checkboxes">
      <input type="checkbox" name="c1" value="1" checked="checked" /> Item 1 <br />
      <input type="checkbox" name="c2" value="1" checked="checked" /> Item 2 <br />
      <input type="checkbox" name="c3" value="1" /> Item 3 <br />
      <input type="checkbox" name="c4" value="1" /> Item 4 <br />
   </fieldset>
[-]View Code JAVASCRIPT
var fieldset_of_all_checkboxes=document.getElementById("all_checkboxes");
var array_of_checkboxes=fieldset_of_all_checkboxes.getElementsByTagName("input");
for(checkbox in array_of_checkboxes)
{
array_of_checkboxes[checkbox].click();
}

With this method, you don’t have to find if the checkbox is in checked or unchecked state!

Written by Rohan Shenoy

November 4th, 2008 at 9:38 pm

Posted in JavaScript/AJAX

Leave a Reply