How to call onclick function on dynamically created button in javascript

var del = document.createElement('input'); del.type = 'button'; del.name = 'delll'; del.value = 'del'; del.onClick = 'alert("hi javascript")'; 

Here I dynamically create a BUTTON of input type and now I want to call a function when a button is clicked. For this, I use the onClick(); function onClick(); . Everything works fine in the above code, but del.onclick doesn’t work the way I want (to create a warning for demonstration)

I do not use any jquery code in this program, so please do not use jquery code.

+8
javascript button dynamically-generated
source share
4 answers

set onclick (all lowercase) to anonymous function

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

Note that the function is not included in quotation marks, such as other attributes

+6
source share
 del.onclick = function () { alert("hi jaavscript"); }; 

Use the little "C" in onClick and pass it a function.

Demo here

+3
source share

try it

  var del = document.createElement('input'); del.setAttribute('type', 'button'); del.setAttribute('name', 'delll'); del.setAttribute('value', 'del'); del.setAttribute('onClick', 'alert("hi jaavscript")'); 
+1
source share

So, to answer the question in detail:

del.onclick = '' does not "execute" something inside quotation marks. If you want to execute / call a function, you need to pass the function as a parameter.

i.e

 del.onclick = function() { alert('hi there!')} 
0
source share

All Articles