tags:

views:

815

answers:

3

I have a table with multiple rows and columns populated by php and mySQL. For some of the td's I'm adding jQuery click-events in the document.ready function to let the user change the content.

But I also have an option for adding rows to the table and populating them manually. But since the rows I'm adding aren't there on the document ready, they won't get the click event handler appended, and so I'm not able to click them to get input boxes.

<table>
  <tr>
    <td class="clickable">Some info</td>
    <td class="clickable">Some more info</td>
    <td>Unchangable info</td>
  </tr>
  ... more similar rows ...
</table>

and then the jQuery

$("tr.clickable").click(function() {
   //add input fields
}

$("span#addNewRow").click(function() {
   $("table").append('<tr><td class="clickable"></td> ... </tr>')
}
+9  A: 

You want to use live events, which were introduced in 1.3.

$("tr.clickable").live("click", function() {
   //add input fields
});

$("span#addNewRow").live("click", function() {
   $("table").append('<tr><td class="clickable"></td> ... </tr>')
});
Plutor
A: 

Use the live event handler. It doesn't handle all events, but it does handle the click event. The handler will be bound to all current and future elements that match the selector.

$('tr.clickable').live( 'click', function() {
   ...
});
tvanfosson
A: 

You would have to add the event listeners after the elements are inserted.

If you are using JQuery you could use the jQuery library livequery which allows you to add events to elements that are not yet in the dom so that you dont have to rebind events when you insert something new into the dom.

Rigobert Song