-2

I have a script that clones the last table row and inserts it at the bottom of my table by clicking a [+] icon. What I'd like to do is allow the removal of the last table row by clicking an [-] icon. Is this possible and if so, could someone point me in the right direction?

<script type="text/javascript">
$(document).ready(function() {
    $("#add").click(function() {
        $('#mytable tbody>tr:last').clone(true).insertAfter('#mytable tbody>tr:last');
        $('#mytable tbody>tr:last #itemid').val('');
        $('#mytable tbody>tr:last #itemdesc').val('');
        return false;
    });
});
</script>
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

3 Answers3

2

The .remove() method is what you're looking for:

$("#remove").click(function(e) {
    e.preventDefault();
    $('#mytable > tbody > tr:last-child').remove();
});

The e.preventDefault() is to prevent the default action of the element (whether it's a button or a link). I'm assuming that there is a default action, since you're using return false; in the original add code.

(Side note: event.preventDefault() vs. return false)

Also, I'm using :last-child here instead of :last for better performance:

Because :last is a jQuery extension and not part of the CSS specification, queries using :last cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. To achieve the best performance when using :last to select elements, first select the elements using a pure CSS selector, then use .filter(":last").

Since the pure CSS selector works in this case (assuming you have a well-formed table), there is no need to .filter(':last'). You should also be able to do this in your #add code when cloning the last row.

Community
  • 1
  • 1
rink.attendant.6
  • 44,500
  • 61
  • 101
  • 156
1

Yes, jQuery has a function called .remove():

$("#remove").click(function(e) {
        $('#mytable tbody>tr:last').remove();
        e.preventDefault(); // dont use return false, use preventDefault();
    });
});

Here you can find some info why you should not user return false; unless you know what you are doing

You could make it a bit more faster

$("#remove").click(function(e) {
        $('#mytable tbody tr').filter(':last').remove();
        e.preventDefault();
    });
});
Martijn
  • 15,791
  • 4
  • 36
  • 68
1

Use jQuery .remove():

$("#remove").click(function(e) {
    e.preventDefault();
    $('#mytable tbody>tr:last').remove();
});
Curtis
  • 101,612
  • 66
  • 270
  • 352