I have ajax method that populates row in table with json data
$.ajax({
url: '@Url.Action("Method", "Controller")',
type: 'GET',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
$.each(data, function (i, item) {
$('#mp tr:eq(1) td:eq(1)').html(item).appendTo('#data');
});
}
});
My row in table after executing method (two items in json):
<table id="mp">
<tr id="data">
<td>Data</td>
<td></td>
<td></td>
<td>56</td>
<td>85</td>
<tr></tr>
</table>
But if there only 2 items in json data they appears in last 2 columns of row after populating, but first two columns is empty. How to populate first columns, not last ones? To look like this:
<table id="mp">
<tr id="data">
<td>Data</td>
<td>56</td>
<td>85</td>
<td></td>
<td></td>
</tr>
<tr></tr>
</table>
The problem is the appendTo()
which will move the element to the last position in the tr
Try to access the td
using the index of the current data item
$.ajax({
url: '@Url.Action("Method", "Controller")',
type: 'GET',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
var $tds = $('#data td');
$.each(data, function (i, item) {
$tds.eq(i + 1).html(item);
});
}
})