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

marcadian
  • 2,608
  • 13
  • 20
user2750762
  • 419
  • 2
  • 6
  • 24
  • Take a look at this answer http://stackoverflow.com/questions/6956258/adding-onclick-event-to-dynamically-added-button – Neeraj Sep 16 '13 at 06:35

4 Answers4

7

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

Paul Nelson
  • 137
  • 4
3
del.onclick = function () {
    alert("hi  jaavscript");
};

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

Demo here

Sergio
  • 28,539
  • 11
  • 85
  • 132
1

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")');
Nitish
  • 776
  • 3
  • 13
0

So to answer the question in details:

del.onclick = '' does not "execute" something within quotes. If you want to execute/call a function, you would want to pass the function as a parameter.

i.e

del.onclick = function() { alert('hi there!')}
Neeraj
  • 8,408
  • 8
  • 41
  • 69