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
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()" />';
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With