user544079
user544079

Reputation: 16629

jQuery selector not firing after dynamically adding a row to a table

I have a table as

<table id="table1">
   <tr>
      <td>Cell 1</td>
      <td>Cell2</td>
   </tr>
</table>

On selecting a cell

$('#table1 tr td').bind('click', function(){
     alert('Selected');
})

However, when I add a cell dynamically

$(this.parentNode).after('<tr><td>Cell 3</td><td>Cell 4</td></tr>');

Now, when I click the Cell 3 or Cell 4, the alert message is not fired.

How can this be fixed without refreshing the page?

Upvotes: 1

Views: 38

Answers (3)

user2699477
user2699477

Reputation:

You will have to reassign the event listeners to the new DOM nodes too. Right after dinamically adding a cell, make sure you set a listener on it too.

jQuery docs: Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on().

Or you could use delegated events along with jQuery's on, as other users suggested. All you have to do is to figure out which element that is closer to the core document in the DOM than your cells are, is surely to be present as a real node by the time you attach the events. In your case, it would be best to choose the document itself as you will not need to wait for the whole DOM to load.

Now, just set the click event to the document. So everytime a click event will get to the document (by directly clicking it or by bubbling to it), the callback will be fired. But we don't want that. Well, it's simple. Just pass one more argument to the .on() method, between the event name and the callback. This argument will be a selector string pointing to the descendants which will be allowed to bubble this specific event up to the document.

Upvotes: 0

sleepwalker
sleepwalker

Reputation: 1032

User jquery "on" method instead of bind. https://api.jquery.com/on/ It's main dif from bind is that it performs kind of watch for element in selector and add 'live bind'. Here is the sample: http://jsbin.com/yapiheju/1/edit

Upvotes: 1

Mariatta
Mariatta

Reputation: 708

Use the jquery on

eg.

$(document).on("click", 
    "#table1 tr td", function(){ 
    alert('Selected'); 
}); 

Documentation here: http://api.jquery.com/on/

Upvotes: 0

Related Questions