Ajay_Dhama
Ajay_Dhama

Reputation: 13

How to set onclick property to dynamically generated input box

Initially I have a table with a certain number of rows and some columns containing input controls with click event handlers.

When I add rows dynamically into the table, how could I set the onclick property to the input controls of the dynamically generated rows?

Upvotes: 0

Views: 451

Answers (3)

Shluch
Shluch

Reputation: 453

You can get all the input elements in your document and manipulate them, using this code:

for (a in each=document.getElementsByTagName('input')) { 
console.log(each[a])
) }

Upvotes: 0

Arindam
Arindam

Reputation: 998

Assumptions

  1. you are using jquery

  2. some jquery block on some condition is adding some more element.

The jquery live and better on functions help you with that.

$('input.yourClass').live('click', function(e) {
  // your code
});

OR

$(document).on('click', 'yourClass', function(e) {
// your code
});

should do the trick.

If you are not using jquery, life can be a tad difficult!

Upvotes: 0

Minko Gechev
Minko Gechev

Reputation: 25682

You should use something like this:

var input = document.createElement('input');
input.type = 'button';
cell.appendChild(input);
input.onclick = function () {
   alert('Clicked!');
};

Here is an example in jsfiddle.

Upvotes: 3

Related Questions