When inside the forEach
callback, this
does not point to a DOM element. It does not hold any useful value.
Furthermore, you are immediately invoking cbChange
and passing its return value to addEventListener
, which is undefined
. However, addEventListener
expects a function as an argument, so you should either pass cbChange
or a function that calls cbChange
.
Lastly, although it's possible to define the event handler to accept the element as the first argument, it's easier if it accepts the event object, as that is the default API behavior.
All things considered, the most straightforward solution would be:
var checkboxes = document.getElementsByClassName('cb');
Array.from(checkboxes).forEach(function(element){
// ^^^^^^^
element.addEventListener("change", cbChange, false);
//^^^^^^^
});
function cbChange(){
console.log(this.value);
// ^^^^
}
Within an event handler, this
represents the element the handler is attached to, making the use of this
inside cbChange
effective.
Here are some alternative approaches:
// Utilize the event object
var checkboxes = document.getElementsByClassName('cb');
Array.from(checkboxes).forEach(function(element){
element.addEventListener("change", cbChange, false);
});
function cbChange(event){
console.log(event.target.value);
}
// Implementing a wrapper that invokes `cbChange`
var checkboxes = document.getElementsByClassName('cb');
Array.from(checkboxes).forEach(function(element){
element.addEventListener("change", function() { cbChange(this); }, false);
});
function cbChange(ele){
console.log(ele.value);
}