2

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); }); 

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

That did it! Thanks a bunch.
0
console.log($newTr[i]); 

Add this after line 15 and you'll see the issue.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.