2

I have some code that allows for a specific table to have the last row duplicated:

<script>
    $(document).ready(function() {
        $(".addbutton").click(function() {
            $('#mytable tbody>tr:last').clone(true).insertAfter('#mytable tbody>tr:last');
            return false;
        });
    });
</script>

So that works for my table with ID of mytable. See working JSFiddle here

What I want to do is make the code work for any table on the same page. So I would have multiple add buttons - and when you press add it will make the closet table row duplicate.

This is what I tried to guess - but it doesnt work

<script>
    $(document).ready(function() {
        $(".addbutton").click(function() {
            $(this).closest('table tbody>tr:last').clone(true).insertAfter($(this).closest('table tbody>tr:last'));
            return false;
        });
    });
</script>

How do I make the code work for multiple tables on the same page? JSFiddle of what I currently have that does not work...

Laurence
  • 58,936
  • 21
  • 171
  • 212

2 Answers2

1

According to your HTML structure, you cannot use closest(), but you need to use the prev() method, using a delegated click event on each .addbutton button:

$(document).on('click', '.addbutton', function(e) {
    e.preventDefault(); // not really needed..depends on situation 
    var $tr = $(this).prev('table').find('tbody > tr:last');
    $tr.clone(true).insertAfter($tr);
});

DEMO

closest() goes upwards in the DOM hierarchy, and the table element you are seeking isn't there, but it is actually a sibling of the "add" button.

vsync
  • 118,978
  • 58
  • 307
  • 400
0

This will help you.

$(document).ready(function(){
  $('.btn').click(function(){
    var tr = $(this).prev('table').find('tr:last');
    tr.clone(true).insertAfter(tr);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table class="table">
    <thead>
        <td>Lorem</td>
        <td>Ipsum</td>
    </thead>
        <tr>
            <td>Consequetor</td>
            <td>...</td>
        </tr>
        <tr>
            <td>Cloning</td>
            <td>....</td>
        </tr>
</table>
<button class="btn">Add</button>
<table class="table">
    <thead>
        <td>Lorem</td>
        <td>Ipsum</td>
    </thead>
        <tr>
            <td>Consequetor</td>
            <td>...</td>
        </tr>
        <tr>
            <td>Cloning</td>
            <td>....</td>
        </tr>
</table>
<button class="btn">Add</button>
Pradeep Rajput
  • 724
  • 7
  • 11