john F. john F. - 16 days ago 7
HTML Question

append method in jquery is only showing the last element added

I'm trying to add data to a table from a json request. Whatever I seem to try I can't get more than one table row to show. Any help would be appreciated.JSFiddle

HTML:

<div class="col-lg-6">
<h2>Table</h2>
<table class="table" id="products-table">
<thead>
<tr>
<th>ASIN</th>
<th>Title</th>
<th>Price</th>
<th>MPN</th>
</tr>
</thead>
<tbody>
<tr></tr>
</tbody>
</table>
</div>


Javascript:

var prodAry = [1, 2, 3];
// create elements for table
var $tr = $('<tr>');
var $asin = $('<td>');
var $title = $('<td>');
var $price = $('<td>');
var $mpn = $('<td>');

prodAry.forEach(function(product, i) {
var $newAsin = $asin.text(i);
var $newTitle = $title.text(i);
var $newPrice = $price.text(i);
var $newMpn = $mpn.text(i);
var $newTr = $tr.append($newAsin, $newTitle, $newPrice, $newMpn);
$('#products-table > tbody:last-child').append($newTr);
});

Answer

As per you current implementation you are continuously appending the same $tr element.

You should create element inside the forEach loop.

var prodAry = [1, 2, 3];
prodAry.forEach(function(product, i) {
    // create elements for table
    var $tr = $('<tr>');
    var $asin = $('<td>');
    var $title = $('<td>');
    var $price = $('<td>');
    var $mpn = $('<td>');

    var $newAsin = $asin.text(i);
    var $newTitle = $title.text(i);
    var $newPrice = $price.text(i);
    var $newMpn = $mpn.text(i);
    var $newTr = $tr.append($newAsin, $newTitle, $newPrice, $newMpn);
    $('#products-table > tbody:last-child').append($newTr);
});

Updated Fiddle