0

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?

2 Answers 2

3
var span = document.getElementById("WD67"); span.onchange = function(){ alert('hello'); }; 
Sign up to request clarification or add additional context in comments.

2 Comments

jsfiddle.net/Paulpro/2MM9H Does that work for you? Which version of IE are you using?
Yes it is.. It was the bug in my test page that was hindering yesterday. Thanks.
1

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

5 Comments

Hi this actually throws an error, - not enough arguments. Same thing happens when trying out on the site you have mentioned too. I'm not able to identify. Could you please check?
You're running firefox, I suppose? obj.addEventListener(htype, fn, true); should do the trick there. See also: jsfiddle.net/PRAd3
I did try that, but In both, Firefox and IE the error is thrown.
Maybe a cache problem? In my IE (8,9) and Firefox (5.0) I don't see problems
You are right mate. There was an issue in the test page I was using that prevented the functions. Thanks for the solution.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.