user2770687
user2770687

Reputation: 21

Create button dynamically and assign a function to it

I am populating a table with a function using JS, and want a button I'm creating as part of the table to call a function when it's clicked. Every time I try to assign a function to the button, the function gets called during creation and then the button does not work once the table is populated. I have tried:

button = document.createElement("BUTTON");
buttonText = document.createTextNode("Edit");
button.setAttribute("name",name);
button.appendChild(buttonText);
button.type = "button";
button.onclick = new function(){alert('clicked');};

And I've tried:

button = document.createElement("BUTTON");
buttonText = document.createTextNode("Edit");
button.setAttribute("name",name);
button.appendChild(buttonText);
button.type = "button";
button.setAttribute('onclick', new function(){alert('clicked');};

Neither one allow this function to be executed when the button is clicked after the table has been created. (But does execute while the button is being created.) I'm sure this is relatively straight-forward, but how do I assign a function to the onclick event of the button in my table? Most everything I have found in the documentation, and on these forums says to use the methods above. All help is much appreciated!

Upvotes: 1

Views: 3822

Answers (1)

nzn
nzn

Reputation: 838

try to change

button.onclick = new function(){alert('clicked');};

into

button.onclick = function(){alert('clicked');};

Upvotes: 2

Related Questions