Onilol Onilol - 7 months ago 29
Javascript Question

Clone image from different row in table

I have this table structure here:

<table id="all-prods" class="table bordered">
<tbody>
<tr class="product">
<td>
<img src="test" />
</td>
<td>Product Title</td>
<td style="text-align:right">
<button type="button" name="click_me">Check out the Variants!</button>
</td>
</tr>
<tr style="display:none">
<td><b>Variant:</b></td>
<td><b>Price:</b></td>
<td><b>Quantity:</b></td>
</tr>
<tr class="table-odd" style="display:none">
<td>Variant title</td>
<td>Variant price</td>
<td style="text-align:right;">
<input id="variant-x" class="quantity field"/>
<button style="text-align:right" type="button" name="addItem">Add</button>
</td>
</tr>
</tbody>
</table>


It's designed to be 1 row for each product , with subrows for each variant.
The contents of this table are being cloned to this one:

<table id="items" class="table bordered hidden">
<thead>
<tr>
<th>Item image:</th>
<th>Item:</th>
<th>Price:</th>
<th>Quantity:</th>
</tr>
</thead>
<tbody>
</tbody>
</table>


I can clone the variant's data with this script here:

<script>
var clone = $(this).closest('tr').clone(true);
clone.appendTo('#items tbody');
</script>


Thing is.. I can't find a way to copy the product's image as the first column in the second table.

I've tried this:Updated JSFiddle link approach but it seems like I'm failing to find the element.

Update
Script at the moment looks like this:

$("button[name='addItem']").click(function(){
var clone = $(this).closest('tr').clone(true);
var img = $(this).closest('tr').prev('tr').find('img').clone(true);
img = img.wrap("<td></td>");
img.prependTo(clone);
clone.appendTo('#items tbody');
})


Could someone help?

Answer

Try like following.

$("button[name='addItem']").click(function () {
    var clone = $(this).closest('tr').clone();
    clone.prepend('<td>' + $(this).closest('tr').prevAll('.product:last').find('img')[0].outerHTML + '</td>')
    clone.appendTo('#wholesale-items tbody');
})

DEMO