views:

71

answers:

1

i have an html table. here is a simplified version:

<table>
      <tr>
           <td><div style="display: none;" class="remove0">Remove Me</div></td>
      </tr>
      <tr>
           <td><div style="display: none;" class="remove1">Remove Me</div></td>
      </tr>
      <tr>
           <td><div class="remove2">Remove Me</div></td>
      </tr>
</table>

i have javascript that clicks on Remove Me in the last row and it deletes the html row using:

$(this).parents("tr:first").remove();

the issue is that when i remove this last row, i also want the "Remove Me" text to now show up on the second row (which is now the new last row). how would i show this div so that it would dynamically show the "remove me" from the new last row?

+3  A: 

Try this. Give all the divs the same class - it'll be much simpler in the long run.

<table>
  <tr>
       <td><div class="remove">Remove Me</div></td>
  </tr>
  <tr>
       <td><div class="remove">Remove Me</div></td>
  </tr>
  <tr>
       <td><div class="remove">Remove Me</div></td>
  </tr>
</table>

And this javascript:

$('.remove')
    .click(function() {
        var $tr = $(this).closest('tr');
        $tr
            .prev()
            .find('.remove')
            .show()
        ;
        $tr.remove();
    })
    // hide all but the last one
    .slice(0, -1).hide()
;
nickf
+1, that is such an elegant solution @nickf.
griegs
excellent solution . . . works like a charm . .
ooo
@oo Another way to do it would be to have only one "remove" link and when you click it, it moves itself into the previous row. Let me know if you'd like to know how to do that.
nickf