I have just needed a toggling function made with javascript for checkboxes wich are grouped in lists. It should look like a hierarchical tree-like structure. When I check the box of my first tree-category, all related subcategories automatically must getting checked too.
I have used the prototype framework for other functionalities on the website, so I preferred to take use of it for helping me by developing this. Prototype framework comes with form functions like getInputs(), but this function gets completely all input fields of a form and not from a specified list, so this did not help me in this situation.
This is a silhouetted visualization of my grouped checkboxes:
- [x] Category 1
- [x] product 1
- [x] product 2
- [x] product 3
- [ ] Category 2
- [ ] product 1
- [ ] product 2
- [ ] product 3
So lets take a look at the code…
I think I dont need to tell that its almost important embedding the prototype framework to your sourcecode.
Here we have the HTML code of the checkboxes:
I want to toggle checking and unchecking all boxes related to Category_1 by clicking the Category_1 checkbox. This Category checkbox needs to get an id. All related input fields will get a class name (wich must be the same as the id of the Category checkbox) for identifying them later.
The Categories input field gets an onClick method wich is calling the javascript function that handles the toggling of the related checkboxes. The given parameter is the class name of the related input fields.
Here we have the javascript function:
At first this function gets all input fields with the given class name and saves them to the variable checkboxes. Then it takes a look at the Category´s checkbox and inspects it if checked or not. If its checked, all the related boxes with the given class name will getting checked too. If its not checked, all related checkboxes are getting unchecked.
Thats all and I hope you can take use of it!