I'm looking for a clean and concise way to add event listeners to each of my checkboxes without having to repeat my Javascript code, I'm still wet behind the ears when it comes to JS, so any assistance would be greatly appreciated.
Here's what I have so far
function exFunction() {};
// on-click
var x = document.getElementById("checkboxopt");
x.addEventListener("click", function(){
console.log("Opt");
});
var y = document.getElementById("checkboxopt1");
y.addEventListener("click", function(){
console.log("Opt 1");
});
var z = document.getElementById("checkboxopt2");
z.addEventListener("click", function(){
console.log("Opt 2");
});
<div id=""><input name="checkboxopt" id="checkboxopt" value="true" type="checkbox"><br/></div>
<div id=""><input name="checkboxopt" id="checkboxopt1" value="true" type="checkbox"><br/></div>
<div id=""><input name="checkboxopt" id="checkboxopt2" value="true" type="checkbox"><br/></div>
Either select all and loop over the collection and add the events to each element in the collection.
var cbs = document.querySelectorAll('[type="checkbox"]');
[].forEach.call(cbs, function (cb) {
cb.addEventListener("click", function(){
console.log(this.id);
});
});
<div id="wrap">
<div id="">
<input name="checkboxopt" id="checkboxopt" value="true" type="checkbox">
</div>
<div id="">
<input name="checkboxopt" id="checkboxopt1" value="true" type="checkbox">
</div>
<div id="">
<input name="checkboxopt" id="checkboxopt2" value="true" type="checkbox">
</div>
</div>
or event delegation and use the event object to figure out what element was clicked.
var wrapper = document.getElementById('wrap');
wrapper.addEventListener("click", function (evt) {
var elem = evt.target;
if (elem.name==="checkboxopt") {
console.log(elem.id);
}
});
<div id="wrap">
<div id="">
<input name="checkboxopt" id="checkboxopt" value="true" type="checkbox">
</div>
<div id="">
<input name="checkboxopt" id="checkboxopt1" value="true" type="checkbox">
</div>
<div id="">
<input name="checkboxopt" id="checkboxopt2" value="true" type="checkbox">
</div>
</div>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments