views:

105

answers:

3

I have some code that dynamically creates a new button through JavaScript that when clicked calls a JavaScript function. The code works just as expected in Firefox, Chrome, Opera but low and behold, it doesn't work in IE(7 - I'm not even going to bother with IE6).

The button gets created and appears, but it's not calling the onclick event.

var newButton = document.createElement('input');
newButton.setAttribute('id','btnChat_');
newButton.setAttribute('type','button');
newButton.setAttribute('onclick','askQuestion()');
newButton.setAttribute('value', 'Respond');
document.getElementById('frmChat').appendChild(newButton);

Does anyone know why this won't work in IE, or have a suggestion as to how I could write this code so it will work?

Thanks.

A: 

Hi,

That will work in firefox, IE is slightly different try

newButton.onclick = function() {askQuestion();};

OR

newButton.onclick = new Function('askQuestion()');

That should work as I have gotten it to work. If that STILL doesn't do it, then YUI has an event framework in which you would do this

YAHOO.util.Event.addListener(newButton,'click',askQuestion);

See http://developer.yahoo.com/yui/examples/event/eventsimple.html for more examples.

Zoidberg
No love with either of those.
Ryan Smith
Made a couple edits, try it now.
Zoidberg
Damn, someone beat me too it!!
Zoidberg
A: 

If you can use jQuery, use it. Not only will this make manipulating the DOM easier, it will let you simply say $('#myNewButton').click(function(){//hey});

and be sure it works.

jQuery.

Stefan Kendall
Yes, it would easier to use jQuery, but this is a generic JavaScript question - and jQuery isn't practical in every environment.
Jason Berry
I would like to do more with JQuery, but I have a pretty good understanding of how to do things in JavaScript without, so that's how I usually approach things. One of these days I'll get around to deeply understanding JQuery.
Ryan Smith
Not knowing is the worst reason for not using. Spend the 30 minutes to sharpen the axe before taking down the great oak. Please.@Jason: Sure, it's not appropriate where jquery isn't possible (a browserless javascript parser, for instance), but that clearly isn't the case here.
Stefan Kendall
In this case, not knowing is a very good reason because I'm doing some pretty crazy interactions with AJAX and other things where I really want to be able to understand what's going on at the lower level. I think JQuery would abstract too much of that away for me and end up causing me problems of leaky abstractions.Also, this is on a very tight deadline, so at the moment there isn't enough time to "sharpen the axe" and still get the project out the door on time.
Ryan Smith
+3  A: 

You could try avoiding use of setAttribute and just do

newButton.onclick = function(){ askQuestion(); };
Brian
Bug: you can't set any inline event handlers using setAttribute() in IE.
scunliffe