You could use querySelectorAll
const checkboxes = document.querySelectorAll( '.example input[type=checkbox]' );
var myFunction = function() {
var attribute = this.getAttribute("data-myattribute");
console.log( attribute );
};
for (var i = 0; i < checkboxes.length; i++) {
checkboxes[i].addEventListener('click', myFunction, false);
}
<div class="example">
<input type="checkbox" data-myattribute="1" />
<input type="checkbox" data-myattribute="2" />
</div>
Or you could just use the event.target
property of your old event listener like this:
var classname = document.getElementsByClassName("example");
var myFunction = function(event) {
var attribute = event.target.getAttribute("data-myattribute");
console.log(attribute);
};
for (var i = 0; i < classname.length; i++) {
classname[i].addEventListener('click', myFunction, false);
}
<div class="example">
<input type="checkbox" data-myattribute="1" />
<input type="checkbox" data-myattribute="2" />
</div>
Of course, with the second approach you need to check, if you really deal with a checkbox.
In your case though I would rather use change events instead of click. That way, you can use it within a label and have the label clickable, instead of only the checkbox itself.
const checkboxes = document.querySelectorAll( '.example input[type=checkbox]' );
var myFunction = function( event ) {
var attribute = event.target.getAttribute("data-myattribute");
console.log( attribute );
};
for (var i = 0; i < checkboxes.length; i++) {
checkboxes[i].addEventListener('change', myFunction, false);
}
<div class="example">
<label>
<input type="checkbox" data-myattribute="1" /> test1
</label>
<label>
<input type="checkbox" data-myattribute="2" /> test2
</label>
</div>