Adding onclick event handler to dynamically added button?
Asked Answered
T

10

21

I am adding a button dynamically to HTML as shown below.

When clicking 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;

How can this be resolved?

Topmost answered 5/8, 2011 at 12:28 Comment(0)
R
28

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()" />';
Relief answered 5/8, 2011 at 12:36 Comment(4)
dude everything is ok.. But I am not able to give the ID by concatinating the string : but and inc... Plz help...... "but' + inc +'" this is not workingTopmost
try : span.firstChild.setAttribute("but" + inc); after the span.innerHTML, also i assume that inc is a variable, and that must be set before it is used. let me know it still doesn't work for you.Relief
how to add params to callJavascriptFunction() like callJavascriptFunction(p1,p2,p3)Katiakatie
It works, but how! What's the difference between btn.onclick = function_name(); and btn.onclick = function_name.Venge
S
16

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;
Solley answered 5/8, 2011 at 12:30 Comment(2)
Why the setAttribute when you also do onclick? Dont all browsers just support onclick?Kicker
when sending a parameter for function how to call functionCollodion
B
11

This code work good to me and look more simple. Necessary to call a function with specific parameter.

var btn = document.createElement("BUTTON");  //<button> element
var t = document.createTextNode("MyButton"); // Create a text node
btn.appendChild(t);   

btn.onclick = function(){myFunction(myparameter)};  
document.getElementById("myView").appendChild(btn);//to show on myView
Burson answered 28/8, 2015 at 9:12 Comment(0)
G
6

Try
but.addEventListener('click', yourFunction) Note the absence of parantheses () after the function name. This is because you are assigning the function, not calling it.

Glair answered 5/8, 2011 at 12:37 Comment(0)
C
5

but.onclick = function() { yourjavascriptfunction();};

or

but.onclick = function() { functionwithparam(param);};

Curlicue answered 25/6, 2017 at 23:0 Comment(1)
> The significant drawback with inline events is that unlike event listeners described above, you may only have one inline event assigned. Inline events are stored as an attribute/property of the element[doc], meaning that it can be overwritten. (https://mcmap.net/q/53240/-addeventlistener-vs-onclick)Flip
G
3

I was having a similar issue but none of these fixes worked. The problem was that my button was not yet on the page. The fix for this ended up being going from this:

//Bad code.
var btn = document.createElement('button');
btn.onClick = function() {  console.log("hey");  }

to this:

//Working Code.  I don't like it, but it works. 
var btn = document.createElement('button');
var wrapper = document.createElement('div');
wrapper.appendChild(btn);

document.body.appendChild(wrapper);
var buttons = wrapper.getElementsByTagName("BUTTON");
buttons[0].onclick = function(){  console.log("hey");  }

I have no clue at all why this works. Adding the button to the page and referring to it any other way did not work.

Grishilde answered 26/8, 2015 at 0:17 Comment(1)
I made this answer a very long time ago, and would no longer recommend it. Instead, use btn.addEventListener('click', function(event){ do stuff });Grishilde
L
2

Try this:

var inputTag = document.createElement("div");              
inputTag.innerHTML = "<input type = 'button' value = 'oooh' onClick = 'your_function_name()'>";    
document.body.appendChild(inputTag);

This creates a button inside a DIV which works perfectly!

Laurentian answered 2/12, 2012 at 23:7 Comment(0)
L
1
but.onclick = callJavascriptFunction;

no double quotes no parentheses.

Lonni answered 5/8, 2011 at 12:33 Comment(1)
what if you want arguments?Jeseniajesh
S
0

Using modern JavaScript, this solution works well:

let btn = document.getElementById("btnID");
btn.onclick = () => {onAction(url, method);};
Sarcasm answered 24/12, 2021 at 18:28 Comment(0)
I
0

for me this works!

button.onclick = () => (removechore());

Idealize answered 24/12, 2022 at 2:1 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Shumpert

© 2022 - 2024 — McMap. All rights reserved.