Mitch Mitch - 1 year ago 40
jQuery Question

How to add a <tr> to dynamic table with Jquery?

How can I wrap this field array into a

<tr>
element, so the result will be 4 table data fields in one table row?

Json data:

{
"result": {
"rowset": {
"row": [
{
"field": [
{
"content": test1,
"name": "name1"
},
{
"content": "test2",
"name": "name2"
},
{
"content": "test3",
"name": "name3"
},
{
"content": test4,
"name": "name4"
}
]
},
.. etc.


Jquery:

$.getJSON('data/jsondata.json', function(data) {
var rowLength = data.result.rowset.row.length;

for (var i = 0; i < rowLength; i++) {
//$('tbody').append('<tr>');
//var myTr = $('tbody').append('<tr>');

for (j = 0; j < 4; j++) {
$('tbody').append('<td>'+data.result.rowset.row[i].field[j].content+'</td>');

}
}
});

Answer Source

Little adaptation is needed for what you want. Try this:

$.getJSON('data/jsondata.json', function(data) {
    var rowLength = data.result.rowset.row.length;

    for (var i = 0; i < rowLength; i++) {
        var row = data.result.rowset.row[i];
        var myTR = $('<tr>');

        for (j = 0; j < row.field.length; j++) {
            var myTD = $('<td>');
            myTD.text(row.field[j].content);
            myTR.append(myTD);
        }
        $('tbody').append(myTR);
    }
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download