Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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.

like image 608
user2750762 Avatar asked Sep 16 '13 06:09

user2750762


3 Answers

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

like image 182
Paul Nelson Avatar answered Sep 19 '22 08:09

Paul Nelson


del.onclick = function () {
    alert("hi  jaavscript");
};

Use small "C" in onClick and pass a function for it.

Demo here

like image 20
Sergio Avatar answered Sep 21 '22 08:09

Sergio


Try like this

    var del = document.createElement('input');
    del.setAttribute('type', 'button');
    del.setAttribute('name', 'delll');
    del.setAttribute('value', 'del');
    del.setAttribute('onClick', 'alert("hi  jaavscript")');
like image 20
Nitish Avatar answered Sep 22 '22 08:09

Nitish