Table row can't be selected with jquery after append

Hello Javascript Guru People,

I have an interesting problem with a document management system I’m currently working on. I’m using the CodeIgniter framework with plenty of jquery ajax goodness. So here’s the problem…

I pop up a dialog to create a new project. When the details are filled in it makes an ajax call to add the data to the database and also appends that data to a HTML table like this (where plist is a complete table row):


$("#projecttable").find('tbody').append(plist);

Each table row has two icons - one to edit the entry and the other to delete the entry. Each row also has a unique ID (like projectrowNN). On the appended row these icons don’t work until the whole page is refreshed. Logic tells me it’s because jquery sees the DOM as it was when the page was loaded, and when you append a row, jquery only knows about the selectors in the DOM that were there the last time the page was refreshed - like it doesn’t go scan the page every time you give it a selector to do something with.

My question then is - is there any way to make this appended row visible to jquery? Or… am I barking up the wrong tree and it should be visible, so there’s some other issue. There aren’t any errors btw - at least not that firebug can see.

Example one will not work, click can’t be attached as the “appended html” is not available.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
 <script src="jquery-1.4.min.js" type="text/javascript"></script>
 <script type="text/javascript">
  $(document).ready(function() {
   $('#tdone').click(function(){
    alert($(this).html());
   });
   var plist = "<tr><td id='tdone'>Row One - Click me </td></tr>" + 
      "<tr><td id='tdtwo'>Two</td></tr>"
   $("#someTable").find('tbody').append(plist);
  });
 </script>
</head>
<body>
 <table id="someTable">
  <tbody>
 
  </tbody>
 </table>
</body>
</html>

You’ll need to either bind your click events below the append code:


var plist = "<tr><td id='tdone'>Row One - Click me </td></tr>" + 
      "<tr><td id='tdtwo'>Two</td></tr>"
   $("#someTable").find('tbody').append(plist);
 
   $('#tdone').click(function(){
    alert($(this).html());
   });

or use live method to bind your event:


$('#tdone').live('click', function(){
    alert($(this).html());
   });
 
   var plist = "<tr><td id='tdone'>Row One - Click me </td></tr>" + 
      "<tr><td id='tdtwo'>Two</td></tr>"
   $("#someTable").find('tbody').append(plist);

You can read about live here:

Change event, i think still doesn’t work with the select boxes when use live to bind even in 1.4. If some one knows how to do it without using the livequery plugin, please let us know.

Thanks! That’s exactly what I needed. It took about 30 seconds to change the functions to use live() :slight_smile: