6

I have an invoice table. The last four rows are as follows, starting from last: Grand Total, Tax, Subtotal, Add a line link.

So I need to add a row before the "Add a link link row".

This thread Add table row in jQuery shows how to add a row after the last row. I just need to modify it, to add a row before the fourth to last row.

Brian Tompsett - 汤莱恩
  • 5,438
  • 68
  • 55
  • 126
leonel
  • 9,968
  • 20
  • 82
  • 129

4 Answers4

23

how about you add a class to your grand total row

<tr class="grand-total"></tr>

then in jquery you do

$('#myTable tr.grand-total').before('<tr></tr>');

this way you are not doing it based on a position that might be changing, but instead based on something meaningful like 'grand total'

Bassam Mehanni
  • 14,556
  • 2
  • 32
  • 41
11

You want a negative .eq:

$("#table tr").eq(-4).before(
    $("<tr>").append(
        $("<td>") // ...
    )
);
pimvdb
  • 146,912
  • 75
  • 297
  • 349
2

Use .before() instead of .after():

$('#myTable tr:last').before('<tr>...</tr><tr>...</tr>');
Didier Ghys
  • 29,970
  • 9
  • 71
  • 78
2

You can get to the last row and then go up with prev()

$(function(){
   $("#myTable tr:last")
       .prev().prev().prev().prev()
       .after("<tr><td>x</td></tr>");
});
epignosisx
  • 6,062
  • 2
  • 29
  • 31