13

I have a table row which contains a textbox and it has an onclick which displays a JavaScript calendar... I am adding rows to the table with textbox, but I don't know how to attach onclick event to the JavaScript generated textbox...

<input  class="date_size_enquiry" type="text" autocomplete="off"
onclick="displayDatePicker('attendanceDateadd1');" size="21" readonly="readonly"    
maxlength="11" size="11"  name="attendanceDateadd1" id="attendanceDateadd1" 
value="" onblur="per_date()" onchange="fnloadHoliday(this.value);">

And my JavaScript generates a textbox,

    var cell2 = row.insertCell(1);
    cell2.setAttribute('align','center')
    var el = document.createElement('input');
    el.className = "date_size_enquiry";
    el.type = 'text';
    el.name = 'attendanceDateadd' + iteration;
    el.id = 'attendanceDateadd' + iteration;
    el.onClick = //How to call the function displayDatePicker('attendanceDateadd1');
    e1.onblur=??
    e1.onchange=??
    cell2.appendChild(el);
simhumileco
  • 31,877
  • 16
  • 137
  • 115
  • 1
    I believe attaching events dinamically is not cross browser, so you may need to write different code for different browsers. I suggest using a JS libray like JQuery for that purpose. With JQuery it's as simple as this: `$('#elementId').click(function() { /* Do what you want here */});` – Emre Yazici Feb 09 '10 at 05:34
  • 1
    @eyazici: The DOM manipulation strategy the OP is using is safe with the exception of `setAttribute()`. – Asaph Feb 09 '10 at 05:43

4 Answers4

20

Like this:

var el = document.createElement('input');
...
el.onclick = function() {
    displayDatePicker('attendanceDateadd1');
};

BTW: Be careful with case sensitivity in the DOM. It's "onclick", not "onClick".

Asaph
  • 159,146
  • 25
  • 197
  • 199
4

Taking your example, I think you want to do this:

el.onclick = function() { displayDatePicker(el.id); };

The only trick is to realise why you need to wrap your displayDatePicker call in the function() { ... } code. Basically, you need to assign a function to the onclick property, however in order to do this you can't just do el.onclick = displayDatePicker(el.id) since this would tell javascript to execute the displayDatePicker function and assign the result to the onclick handler rather than assigning the function call itself. So to get around this you create an anonymous function that in turn calls your displayDatePicker. Hope that helps.

Alconja
  • 14,834
  • 3
  • 60
  • 61
3
el.onclick = function(){
  displayDatePicker(this.id);
};
Shawn Steward
  • 6,773
  • 3
  • 24
  • 45
3

HTML5/ES6 approach:

var el = document.createElement('input')

[...]

el.addEventListener('click', function () {
  displayDatePicker('attendanceDateadd1')
})
Arthur Ronconi
  • 2,290
  • 25
  • 25