EmptySnake EmptySnake - 1 month ago 8
CSS Question

Duplicate perticular Structure on click with jQuery

That's what I have:
HTML

<div class="table-product-wrap-inner">
<table class="table-product">
<tbody>
<tr>
<td></td>
.........
<td>
<buttom class="btn-copy-link"></button>
</td>
</tr>
</tbody>
</table>
<button class="dont-copy-that-btn></button>
<div class="collapse"></div>
</div>


jQ

init: function () {
var that = this;

this.$productEdit.on('click', '.btn-copy-link', function(){
var $cTable = $(this).closest('.table-product'),
$ele = $cTable.clone(true),
$gName = $ele.find('td:first'),
$lName = $ele.find('.product-link-title'),
$idL = $ele.find('.product-link-id');

$cTable.after($ele);
$gName.empty();
$lName.val($lName.val() + " Копия");
$idL.val('');
});
}


Current function copies the nearest
table
and inserts it after the original but i also need to copy the nearest
div
with class
collapse
and past
table
+
div
after that
collapse
. Copy
button
located in
table
.

Something like this:

<div class="table-product-wrap-inner">
<table class="table-product">
<button class="btn-copy-link"></button>
</table>
<button class="dont-copy-that-btn></button>
<div class="collapse"></div>
</div>


after CLICK:

<div class="table-product-wrap-inner">
<table class="table-product">
<button class="btn-copy-link"></button>
</table>
<button class="dont-copy-that-btn></button>
<div class="collapse"></div>
<!-- COPY-->
<table class="table-product">
<button class="btn-copy-link"></button>
</table>
<div class="collapse"></div>
</div>


If user click
button
again in a first pair of
table
+
div
it duplicate them after that pair. If we click
button
in a second pair - got copy after second one etc etc.

Answer

You can use next() from the closest table element to find the div you need. Try this:

this.$productEdit.on('click', '.btn-copy-link', function(){
    var $cTable = $(this).closest('.table-product'),
        $div = $cTable.next('div.collapsed'),
        $ele = $cTable.clone(true);

    $ele.find('td:first').empty();
    $ele.find('.product-link-title').val($lName.val() + ' Копия');
    $ele.find('.product-link-id').val('');

    $div.after($ele); // insert table clone after previous div
    $ele.after($div.clone(true)); // append cloned div after new table clone
});