yoka yoka - 1 year ago 47
HTML Question

Adding new data from JSON to existing table

I am trying to add new data (from JSON) to existing table (using jquery).

In my html I have this table for example:

<table data-role="table" data-mode="columntoggle" class="ui-responsive" data-column-btn-text="Filter Columns" id="MyTable">
<thead>
<tr>
<th data-priority="1">A</th>
<th data-priority="2">B</th>
<th data-priority="3">C</th>
</tr>
</thead>
<tbody>
<tr>
<td>a1</td>
<td>b1</td>
<td>c1</td>
</tr>
</tbody>
</table>


I am trying to do this (for adding new data from JSON):

var response = [{
"A":"a2",
"B":"b2",
"C":"c2"
},
{
"A":"a3",
"B":"b3",
"C":"c3"
},
{
"A":"a4",
"B":"b4",
"C":"c4"
}];

$.each(response, function(i, item) {
$('<tr>').html(
//"<tr>" +
"<td>" + response[i].A + "</td><td>" + response[i].B + "</td><td>" + response[i].C + "</td>" + "</tr>").appendTo('#MyTable');
});


Why doesn't it work?

Answer Source

You're appending the content to the table itself and not to the thead or tbody elements, which is what should be done. Try changing your selector in .appendTo to #MyTable tbody and it will work. Demo here.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download