Ryan Smith
Ryan Smith

Reputation: 8324

IE Dynamically Added Button Not Calling On Click

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.

Upvotes: 2

Views: 586

Answers (3)

Zoidberg
Zoidberg

Reputation: 10323

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.

Upvotes: 0

Brian
Brian

Reputation: 3601

You could try avoiding use of setAttribute and just do

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

Upvotes: 4

Stefan Kendall
Stefan Kendall

Reputation: 67832

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.

Upvotes: 0

Related Questions