how to call onclick function on dynamically created button in javascript

user2750762 picture user2750762 · Sep 16, 2013 · Viewed 21.2k times · Source
var del = document.createElement('input');
del.type = 'button';
del.name = 'delll';
del.value = 'del';
del.onClick = 'alert("hi  javascript")';

Here I have dynamically created a input type BUTTON and now I want to call function on button click event. I am using onClick(); function for this. In the above code all is working fine but del.onclick is not working as I want (for generating alert for demo)

I am not using any jquery code in this program so please don't use any jquery code.

Answer

Paul Nelson picture Paul Nelson · Sep 16, 2013

set the onclick (all lower case) to an anonymous function

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

note the function is not in quotes like other attributes