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.
Adding new data from JSON to existing table
-
16-07-2023 - |
Question
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?
Solution
OTHER TIPS
You were accessing the object in wrong way.Try this code snippet.
$.each(response, function(i, item) {
$('<tr>').html(
"<td>" + item.A + "</td><td>" + item.B + "</td><td>" + item.C + "</td>" + "</tr>").appendTo('#MyTable tbody');
});
Use $('<tbody>').append instead of $('<tr>').html().
$.each(response, function(i, item) {
$('<tbody>').append(
"<td>" + response[i].A + "</td><td>" + response[i].B + "</td><td>" + response[i].C + "</td>" + "</tr>").appendTo('#MyTable');
});
You can see it in action at this JSFiddle.
Try the following snippet. This creates the 'tr' elements in the html.
$.each(response, function(i, item) {
$("#MyTable tbody").append("<tr> <td>" + response[i].A + "</td><td>" + response[i].B + "</td><td>" + response[i].C + "</td> </tr>");
});
Do this:
table_html = '';
$.each(response, function(index, value) {
table_html += "<tr><td>"+value["A"]+"</td><td>"+value["B"]+"</td><td>"+value["C"]+"</td></tr>"
});
Give some id to <tbody>
tag.
$("tbodyid").html(table_html);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow