arunondeck
arunondeck

Reputation: 368

Adding event handler using javascript doesnt work in IE

I am trying to add an event handler on a page through javascript. What I tried is as follows,

var span=document.getElementById("WD67");  
span.setAttribute("onchange","alert('hello');");

But though the event handler attribute gets added, it doesn't fire when the page is viewed in IE, however in Firefox it works properly. How do I get IE to recognize it?

Upvotes: 0

Views: 994

Answers (2)

KooiInc
KooiInc

Reputation: 122986

Don't use attributes for that. The best way to add event handlers is using addEventListener (all modern browsers) or attachEvent (IE<9). Furthermore, use a handler function reference (wrap alert('hello') in a function).

A crossbrowser function to add handlers to elements:

function addHandler(obj,htype,fn){
    if (obj.addEventListener){
     obj.addEventListener(htype, fn);
    } else {
     obj.attachEvent('on'+htype,fn);
    }
}
// usage
var mySpan=document.getElementById("WD67");
addHandler(mySpan,'change',function(){alert('hello')});

See also: this jsfiddle

Upvotes: 1

Paul
Paul

Reputation: 141917

var span = document.getElementById("WD67");
span.onchange = function(){ alert('hello'); };

Upvotes: 3

Related Questions