Wednesday 30 May 2012

JavaScript: select all checkboxes in a form

   


A common feature in many web site is the possibility of checking a series of checkboxes in just one go. For example, when managing emails in a web site, we can allow the user to select a bunch of messages and move them all together.
How can we create such a toggle all button?
We are going to use a simple JavaScript function. Follow me and see how...
The form
First of let's create a form containing a bunch of checkboxes:
<form name="form1">
  <input type="checkbox" name="chk" value="A">A<br>
  <input type="checkbox" name="chk" value="B">B<br>
  <input type="checkbox" name="chk" value="C">C<br>
  <input type="checkbox" name="chk" value="D">D<br>
  <input type="button" name="selAll" value="Toggle All" onClick="togAll();">
</form>
By pressing the button we trigger the function (togAll()) that will check all the checkboxes.

The function
The function is going through all the checkboxes changing their state (from unchecked to checked) regardless their previous state. Meaning that all the checkboxes will revert to a checked state, even if they were already checked.
<script type="text/javascript">
function togAll()
{
  var i = 0;
  var form1 = document.form1.elements;
   for (i=0; i<form1.length; i++)
    {
      if(form1[i].type == "checkbox")
      {
       form1[i].checked = !(form1[i].checked);
      }
   }
}
</script>
I don't think there's much to say about the togAll() function. It mainly consists in a cycle that goes throught all the elements of the form, it checks if they are checkboxes and it changes the found elements to a checked state.

See you next, and let me know if you've found the idea useful.

0 thoughts:

Post a Comment

Comments are moderated. I apologize if I don't publish comments immediately.

However, I do answer to all the comments.