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,753
  • 72
  • 57
  • 129
leonel
  • 10,106
  • 21
  • 85
  • 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,796
  • 2
  • 33
  • 41
11

You want a negative .eq:

$("#table tr").eq(-4).before(
    $("<tr>").append(
        $("<td>") // ...
    )
);
pimvdb
  • 151,816
  • 78
  • 307
  • 352
2

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

$('#myTable tr:last').before('<tr>...</tr><tr>...</tr>');
Didier Ghys
  • 30,396
  • 9
  • 75
  • 81
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,152
  • 2
  • 30
  • 31