IE Dynamically added button not triggering click

I have code that dynamically creates a new button using JavaScript that, when clicked, calls a JavaScript function. The code works as expected in Firefox, Chrome, Opera, but few, and lo, it doesn't work in IE (7 - I won't even bother with IE6).

The button is created and appears, but does not raise 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 doesn't work in IE, or is there a suggestion on how I can write this code to make it work?

Thank.

+2


source to share


3 answers


You can try to avoid using setAttribute and just do



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

      

+4


source


This will work in firefox, IE is slightly different from

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

      

OR

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

      



This should work as I got it to work. If this STILL does not, then YUI has an event framework in which you will do this

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

      

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

0


source


If you can use jQuery then use it. Not only will this make DOM manipulation easier, it will allow you to just say$('#myNewButton').click(function(){//hey});

and make sure it works.

jQuery .

0


source







All Articles