I am trying to add event listers for all checkboxes inside a class. I am able to add event listener to class. How can I add to all checkboxes inside that class?
var classname = document.getElementsByClassName("classname");
var myFunction = function() {
var attribute = this.getAttribute("data-myattribute");
alert(attribute);
};
for (var i = 0; i < classname.length; i++) {
classname[i].addEventListener('click', myFunction, false);
}
Since JS events bubble up to parent elements you only have to attach ONE event listener to the parent element and it will catch every event triggered by its children.
document.querySelector('#container').onclick = function(ev) {
if(ev.target.value) {
console.log(ev.target.checked, ev.target.value);
}
}
<div id="container">
<input type="checkbox" value="Bike">I have a bike<br>
<input type="checkbox" value="Car">I have a car<br>
<input type="checkbox" value="Flower">I have a flower<br>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With