Pass this to addEventListener() as parameter

Viewed 13590

I want to add change event to a group of checkboxes, how can I access this in my event function, so that when I do the event I can access value of the checkbox.

This is my current code:

var checkboxes = document.getElementsByClassName('cb');
Array.from(checkboxes).forEach(function(){
  this.addEventListener("change", cbChange(this), false);
});

function cbChange(ele){
  console.log(ele.value);
}
<input class="cb" type="checkbox" name="candidate" value="1"/>
<input class="cb" type="checkbox" name="candidate" value="2"/>
<input class="cb" type="checkbox" name="candidate" value="3"/>
<input class="cb" type="checkbox" name="candidate" value="4"/>

5 Answers

From my opinion, i thinks you can use for..of loop to get the value of each checkbox.

var checkboxes = document.getElementsByClassName('cb');
for (let checkboxe of checkboxes ) {
  checkboxe.addEventListener('change', () => {
      console.log(checkboxe.value)
  })
}
Related