Reputation: 18103
Im having a table with 3 rows, with inputs where you can fill values in.
Now I have a link in the last tr, that says "+ More".
The "+ More" link, should if worked as expected, clone the above tr and append it above the link.
This is how far I am:
$(document).ready(function(){
$('.appendRow').bind('click', function(){
var $table = $(this).closest('table');
var $tr = $(this).closest('tr');
var $trAbove = $(this).prev('tr');
$table.append($tr.clone());
});
});
I tried to use prev('tr')
to grab the TR element before the one I am inside, but it does not really work.
The second issue is that it appends under the +More TR, and not above it.
How can this be done?
Upvotes: 0
Views: 827
Reputation: 40639
Try to use on() for dynamically added elements and you HTML should be like,
HTML
<table class="extraBookingBox">
<tr><td>Fees</td><td>Amount</td></tr>
<tr>
<td><input type="text" style="width: 40px;" name="cancelfee_price[]" />€</td>
<td><input type="text" style="width: 40px;" name="cancelfee_price[]" />€</td>
</tr>
<tr>
<td colspan="2"><a href="#" class="appendRow">+ More</a></td>
</tr>
</table>
SCRIPT
$(document).ready(function(){
$(document).on('click','.appendRow', function(){
var $tr = $('table tr:nth-child(2)').clone();
console.log($tr);
$tr.insertBefore($('.appendRow').closest('tr'));
});
});
Upvotes: 0
Reputation: 1074385
The reason that $(this).prev('tr')
doesn't work is that your appendRow
class is on the link, not the row. There is no tr
immediately prior to the link, prev
looks at the previous sibling element (sibling = within the same parent) to see if it matches the selector. It doesn't scan, and it doesn't go up the hierarchy.
You're pretty close though, see comments: Updated Fiddle
$(document).ready(function(){
$('.appendRow').bind('click', function(){
// First get the current row
var $tr = $(this).closest('tr');
// Now the one above it
var $trAbove = $tr.prev('tr');
// Now insert the clone
$trAbove.clone().insertBefore($tr);
});
});
Note the use of insertBefore
, which will insert the clone before the current row.
Upvotes: 3