Here is a quick demo of the select all or none JavaScript function that automatically toggles all of your checkboxes in a given form.
This is the plain HTML of the form:
1 2 3 4 5 6 7 8 | <form name="theForm"> My favorite programming/scripting language is:<p> Select <a href="javascript:selectToggle(true, 'theForm');">All</a> | <a href="javascript:selectToggle(false, 'theForm');">None</a><p> <input type="checkbox" name="answers[]" value="javascript">JavaScript<p> <input type="checkbox" name="answers[]" value="perl">Perl<p> <input type="checkbox" name="answers[]" value="php">PHP<p> <input type="checkbox" name="answers[]" value="c++">C++ </form> |
There is nothing exciting about the HTML code except for line 3 where all the magic happens. There are 2 links in this line of code:
- All - When the user clicks on this link, it will execute the selectToggle() JavaScript function and passes over 2 arguments: the value to set the checkboxes (
truein this case) and the name of the form. - None - This link executes the selectToggle() JavaScript function and passes over the
falsevalue to uncheck the checkboxes and the name of the form.
Here is a peek at the selectToggle() JavaScript function:
1 2 3 4 5 6 7 8 9 10 11 | function selectToggle(toggle, form) { var myForm = document.forms[form]; for( var i=0; i < myForm.length; i++ ) { if(toggle) { myForm.elements[i].checked = "checked"; } else { myForm.elements[i].checked = ""; } } } |
This function basically loops through all of the inputs in the given form name that is passed over as an argument. Depending on the value of the toggle parameter, which can be true or false, each form element will checked or unchecked respectively.
Thank you so much, onclick scripts are confusing, and most do not work, I as a coder can understand this one, and it work perfectly.
Old post but still very effective. This script works perfectly.
Simple, elegant and effective – so refreshing! Thanks for posting.
ยต
[...] and None Checkbox function in javascript JavaScript to select all or none of the checkboxes in a form Here is a quick demo of the select all or none JavaScript function that automatically toggles all [...]
This is a good script, all the others i had found check or uncheck by the name of the checkbox and not by the form name