mardi 29 mai 2012
JavaScript: select all checkboxes in a form
Do you like this story?
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>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>See you next, and let me know if you've found the idea useful.

This post was written by: Franklin Manuel
Franklin Manuel is a professional blogger, web designer and front end web developer. Follow him on Twitter
Inscription à :
Publier les commentaires (Atom)


0 Responses to “JavaScript: select all checkboxes in a form”
Enregistrer un commentaire