Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding onclick event to dynamically added button?

I am adding a button dynamically in html like below: On click of that button I want to call a Javascript function:

var but = document.createElement("button");

but.value="delete row";

but.setAttribute("onclick","callJavascriptFunction()");
//this is not working

but.onclick="callJavascriptFunction()"
//this is also not working

document.getElementById("but").onclick="callJavascriptFunction()"
//this is also not working

but.id="but"+inc;

Are there any ways to resolve this??Plz help me., thanks in advance

like image 493
sanjeev Avatar asked Aug 05 '11 12:08

sanjeev


2 Answers

try this:

but.onclick = callJavascriptFunction;

or create the button by wrapping it with another element and use innerHTML:

var span = document.createElement('span');
span.innerHTML = '<button id="but' + inc +'" onclick="callJavascriptFunction()" />';
like image 142
jerjer Avatar answered Sep 29 '22 10:09

jerjer


Remove the () from your expressions that are not working will get the desired results you need.

but.setAttribute("onclick",callJavascriptFunction);
but.onclick= callJavascriptFunction;
document.getElementById("but").onclick=callJavascriptFunction;
like image 21
Brett Walker Avatar answered Sep 29 '22 09:09

Brett Walker