aug born
aug born

Reputation: 346

Unable to attach click event to a dynamically created button

I have created a javascript function to dynamically create a button

function btn(d) {
    var btn = document.createElement("BUTTON");
    var t = document.createTextNode(d);
    btn.appendChild(t);
    btn.className = "myButton";
    btn.onclick = alert('hello');
    document.body.appendChild(btn);
}

when this function is called, alert is poping up even if button is not clicked. I want the alert when button is clicked. May be i am missing something. Please help. Thanks

Upvotes: 0

Views: 73

Answers (4)

Ted
Ted

Reputation: 14927

Try doing it with jQuery, like so (per your jQuery tag on the question):

function btn(d) {
    var btn = $('<button/>').addClass('myButton').text(d).appendTo('body').click(function (e) {
        alert('hello');
    })
}

Upvotes: 1

Sami Kuhmonen
Sami Kuhmonen

Reputation: 31143

You are assigning the return value of alert('hello'); to the onclick, while it is expecting a function. The correct way without jQuery would be

if (btn.addEventListener)
  btn.addEventListener ('click',function(){ alert('hello');}, false);
else if (btn.attachEvent)
  btn.attachEvent ('onclick',function(){ alert('hello');});

Upvotes: 0

maembe
maembe

Reputation: 1300

onclick should look like:

btn.onclick = function(){alert('hi');};

Upvotes: 0

t3dodson
t3dodson

Reputation: 4007

you are calling the alert function not assigning a function

alert('hello'); // evals immediately.

btn.onclick = function () {
    alert("Hello World"); // gives the button a click handler 
                          // which can be called when clicked
};

Upvotes: 2

Related Questions