JohnSmith JohnSmith - 1 month ago 6
HTML Question

How do I output the contents of an array in an html table while using jQuery?

How do I display the contents of an array in a HTML table while using jQuery?

Here's my script... This outputs the objects in the array on top of the table not in the table.

HTML

<table>
<thead>
<tr>
<th>ITEM ID</th>
<th>NUMBER OF BAGS</th>
<th>WEIGHT</th>
</tr>
</thead>
<tbody>
<div id="returnlist"></div>
</tbody>
</table>


jQuery

var tempList = new Array();
$('#add').click(function(){
var split = $('#onhanditem').val().split('_');
var itemid = split['0'];
var kilo = $('#kilo').val();
var bagsReturned = $('#bagsReturned').val();
var totalbagkiloreturned = kilo+'_'+bagsReturned;
tempList[itemid] = totalbagkiloreturned;
list = '';
// i = ITEM ID | tempList = totalbagkiloreturned
for (var i in tempList){
var itemID = i;
var split = tempList[i].split('_');
var kilo = split['0'];
var numBags = split['1'];
list+='<tr><td>'+itemID+'</td><td>'+kilo+'</td><td>'+numBags+'</td></tr>';
}
$('#returnlist').html(list);
});
});

Answer

As far as I'm aware, the middle of a table isn't a valid location for a <div> tag, which is why it's not being displayed inside the table. Why not put your id on the <tbody> tag instead, and do away with the div altogether?