views:

139

answers:

3

Hi All,

I am trying to add new rows in my table, and save them into DB.

First, I use .append() to append rows on the table:

$("#tablename").append("<tr id='newRow'><td>newly added row</td></tr>");

The appending function works fine. My page displays the correct result.

However, I am unable to select them with

$("#newRow").each(function () { alert "it never reaches here!"; });

I am guessing it is because the elements are added after the DOM is loaded. Can anyone please tell me how I can iterate through all my newly added elements?

Thank you.

+6  A: 

You should use a class for this case, an ID has to be unqiue (it's invalid HTML and will give some weird behavior otherwise), like this:

$("#tablename").append("<tr class='newRow'><td>newly added row</td></tr>");

$(".newRow").each(function () { alert "it never reaches here!"; });
Nick Craver
Thank you. It works like charm now.
jaeyun
A: 

If all you need is to loop the new rows you can do this:

var rows = $("<tr class='newRow'><td>newly added row</td></tr>").appendTo('#tablename');
rows.each(function () { alert "it never reaches here!"; });
PetersenDidIt
This would create invalid HTML...
Nick Craver
Multiple ids? #shame :)
Doug Neiner
I don't understand this answer. To be correct, there would need to be only one `#newRow`, which would seem to make the loop an odd choice.
patrick dw
@Nick @Doug Sorry copied his html that had the ID. My guess is that his real string has more then one row in it.
PetersenDidIt
@Nick @patrick The title for this questions is "jquery iterating through newly created elements" making it seem like he just wants to iterate through the new elements.
PetersenDidIt
+1  A: 

Nick's method works just fine, here's another:

$(function(){
  //add a class to mark the last row on load
  $('#tableName tr:last').addClass('lastRow');

  // ...

  // select new rows when you click save
  $('input:submit').click(function(){
     $('#tableName tr.lastRow').nextAll().each(function(){
        alert('added row');
     });
  });
});
John Rasch