user361697
user361697

Reputation: 1131

jQuery : Dynamic table rows not working with events

I am coding a HTML table of products. There are lot of columns with lot of jQuery events (change, click, etc) attached to form elements (button, text, select) inside each column. They work perfectly fine.

The last column contains "add" link which makes an AJAX callback to a URL that adds a new row dynamically inside the table.

$('table td .addrow').live('click', function() {
  var cur_obj = this;
  $.ajax({
   url: 'product/addrow',
   success: function(data) {
    $(cur_obj).parent().parent().after(data);
   }
  });
 });

The row is getting added dynamically but none of the jQuery events are working even though they work fine with the preloaded rows.

Upvotes: 1

Views: 1299

Answers (3)

Yoosuf Mo
Yoosuf Mo

Reputation: 163

$('table').delegate('td', 'click', function() { //do stuff });

Upvotes: 0

Steve Claridge
Steve Claridge

Reputation: 11100

Shouldn't you be separating your .live() usage from the add link? Sounds like you want the click(), change(), etc events to work the same on all rows so add .live() events to them, something like:

$('table td').live('click', function() {
  //do stuff
});

So the .live() call makes sure you new rows are add to the eventhandlers. If you have an addrow element on each new row that you add then your original code looks OK.

Upvotes: 1

chchrist
chchrist

Reputation: 19842

You should use the live() or the delegate() jQUery functions

Upvotes: 1

Related Questions