1

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?

Dorion
  • 77
  • 1
  • 1
  • 6
  • http://stackoverflow.com/a/27622415/5393271 if you want events just for specific elements – sTx Apr 13 '17 at 15:42

2 Answers2

1

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.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

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.

Abdul Shaikh
  • 129
  • 9