Reputation: 77
I have a container and inside it a bunch of radio and checkboxes. How can I create an onclick handler for the container so that it gets triggered when a checkbox or radio button inside the container is clicked? For exampel, a click might make the container change its css class. Say, if it doesn't have "css_class1", this class gets added to it.
I want to do that in pure javascript.
Is it possible at all or do I have to create an onclick handler for each checkbox and radio individually?
Upvotes: 1
Views: 79
Reputation: 129
I would try something simple like selecting the element by class and creating an on click handler for that. for example
var childrenElements = document.getElementByClass('children');
childrenElements.addEventListener("click", addClass());
function addClass(){
childrenElements.classname="css_class1";
}
What this code would do is simply apply a class to all elements, though if you are interested in applying the classes individually I would recommend getting each element by id as doing it with the class can cause some annoying problems.
Upvotes: 0
Reputation: 944083
You … add a click handler to the container.
That's it.
That's how click handlers work.
function handler(event) {
alert("Click on " + event.target.tagName + " for handler on " + event.currentTarget.tagName);
}
document.querySelector("div").addEventListener("click", handler)
<div>
<input type="radio">
</div>
If you want it to only do something when one of the inputs is clicked: Test the value of event.target.tagName
before continuing with the rest of the function.
Upvotes: 1