There is this question about the clickable label,
what I’m trying to find out how to make clickable labels that are not check-in/out the
checkbox, but trigger separate event which effecting the checkbox.
This is the div with the checkboxes and labels:
<div class="containerSelectBox" id="multi_select"> <input type="checkbox" /><label id="a1"> This is checkbox </label><br/> <input type="checkbox" /><label id="a2"> This is checkbox </label><br/> <input type="checkbox" /><label id="a3"> This is checkbox </label><br/> <input type="checkbox" /><label id="a4"> This is checkbox </label><br/> <input type="checkbox" /><label id="a5"> This is checkbox </label><br/> </div>
What I like to find is when clicking on each label it will for example alert the id of this label.
I can’t just write onclick
on each label I need to attach dynamically to the onclick
event trigger.
Advertisement
Answer
Try this:
const labels = document.querySelectorAll("label"); labels.foreach(label => { label.addEventListener("click", event => { // PUT HERE WHAT YOU WANT TO DO WHEN THE LABEL IS CLICKED }) })