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?
The formFirst of let's create a form containing a bunch of checkboxes:
By pressing the button we trigger the function (togAll()) that will check all the checkboxes.
<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();">
The functionThe 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.
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.
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);
See you next, and let me know if you've found the idea useful.