Controlling Checkboxes with JavaScript
By Will Bontrager2005-06-29
"All" and "None" Checkboxes
The demonstration has checkboxes representing three colors, plus "All" and "None." The "None" checkbox is pre-checked.
The checkboxes representing the three colors can be checked and unchecked individually. If the "All" or the "None" checkbox is checked, all other checkboxes become unchecked.
There will always be at least one checkbox checked.
If "All" or "None" are checked, everything else is unchecked.
If any one or more of the colors are checked, both "All" and "None" are unchecked.
Whenever there is a situation where no checkbox would otherwise be checked, "None" automatically becomes checked.
The JavaScript is four functions, UpdateChecks(), AllIsChecked(), NoneIsChecked(), and BoxesCheck().
The function UpdateChecks() is called every time a checkbox is checked or unchecked. When that function is called, it knows which was checked/unchecked, either the "All," the "None," or one of the color checkboxes.
If it was the "All" checkbox, function AllIsChecked() is called.
If the "All" checkbox happens to be unchecked at the time the function is called, then the function BoxesCheck() is called to handle the situation (see c., below).
If the "All" checkbox happens to be checked, all others are unchecked.
If it was the "None" checkbox, function NoneIsChecked() is called.
If the "None" checkbox happens to be unchecked at the time the function is called, then the function BoxesCheck() is called to handle the situation (see c., below).
If the "None" checkbox happens to be checked, all others are unchecked.
If it was one of the color checkboxes, function BoxesCheck() is called. It
Unchecks the "All" checkbox.
Unchecks the "None" checkbox.
If all the colors are checked, then it
Checks the "All" checkbox, and
Calls the AllIsChecked() function.
If all the colors are unchecked, then it
Checks the "None" checkbox, and
Calls the NoneIsChecked() function.
Now you're on your way to becoming an expert with JavaScript and form checkboxes. It can take a bit of practice, and some trial and error. But once it's understood, you have a skill that can become useful time and again.
Tutorial Pages:
» Controlling Checkboxes with JavaScript
» Limiting the Number of Checkboxes
» Totaling the Value of Checked Checkboxes
» Checking or Unchecking a Group of Checkboxes
» "All" and "None" Checkboxes
Copyright 2004 Bontrager Connection, LLC
