I have a list of input
<ul id="list">
<li><input type="text" /></li>
<li><input type="text" /></li>
<li><input type="text" /></li>
<li><input type="text" /></li>
</ul>
Because there are many of them, I let ul do a event delegation:
function addHandler(element, type, handler) {
if (element.addEventListener) {
element.addEventListener(type, handler, false);
} else if (element.attachEvent) {
element.attachEvent("on" + type, handler);
} else {
element["on" + type] = handler;
}
}
addHandler(document.getElementById("list"), "change", function(event) {
event = event || window.event;
var target = event.target || event.srcElement;
if (target.nodeName === "INPUT") {
alert(target.value);
}
});
This works well in Chrome, Firefox, but not in IE, what’s the problem?
Fiddle: http://jsfiddle.net/94ngc/
The problem is that the
changeevent is buggy in IE<9. Have a look at this chart:http://www.quirksmode.org/dom/events/change.html
As you can see, the change event works in all browsers, but IE only triggers it on the input element (I suppose it just doesn’t bubble correctly, or it is not available for other elements).
Try this as a test, it should work for the fist input in IE:
I suggest you loop through all your inputs and attach the listener to each element instead of delegating the event to the UL, or use an event normalizer like jQuery or YUI.
Note: your code seems to work fine in IE9+