addEventListener not working in IE8

ravi404 picture ravi404 · Mar 19, 2012 · Viewed 116.3k times · Source

I have created a checkbox dynamically. I have used addEventListener to call a function on click of the checkbox, which works in Google Chrome and Firefox but doesn't work in Internet Explorer 8. This is my code:

var _checkbox = document.createElement("input");
_checkbox.addEventListener("click", setCheckedValues, false);

setCheckedValues is my event handler.

Answer

Sudhir Bastakoti picture Sudhir Bastakoti · Mar 19, 2012

Try:

if (_checkbox.addEventListener) {
    _checkbox.addEventListener("click", setCheckedValues, false);
}
else {
    _checkbox.attachEvent("onclick", setCheckedValues);
}

Update:: For Internet Explorer versions prior to IE9, attachEvent method should be used to register the specified listener to the EventTarget it is called on, for others addEventListener should be used.