0
for(var i=0;i<Result.length;i++){
    $('<tr>').appendTo('#resultstable');

    for(var j=0;j<tableID.length;j++){
        $('<td>' + Result[i][tableID[j]] + '</td>').appendTo('#resultstable');
                    }
        $('</tr>').appendTo('#resultstable');

When trying to display a table from JSON data, it displays the headers correctly (not shown here), but when I want the data to show on a new row, it doesn't work. The first row of data is shown correctly, but what should be on the second row continues on from the end of the first row.

In the HTML (when loaded), it shows it as:

..Table headers..
<tbody>
<tr></tr>
</tbody>
<td>1</td>
...Rest of cell data is put in <td> tags...
TheBritishBloke
  • 169
  • 1
  • 2
  • 8
  • possible duplicate of [Add table row in jQuery](http://stackoverflow.com/questions/171027/add-table-row-in-jquery) – Barmar Feb 07 '14 at 16:21
  • 1
    The fact that you think you have to append `` means you don't understand how jQuery appending works. It adds entire DOM elements, it's not concatenating HTML codes. – Barmar Feb 07 '14 at 16:22

4 Answers4

1

That is happening because

$('<tr>').appendTo('#resultstable');

creates <tr></tr> dom element and adds it to #resultstable table.

With this statement

$('<td>' + Result[i][tableID[j]] + '</td>').appendTo('#resultstable');

you are not adding html after <tr>. You are creating td tag and assigning it to #resultstable table. But td tag can be assigned only to tr tag.

So the right syntax will be.

for(var i=0;i<Result.length;i++){
var tr = $('<tr>').appendTo('#resultstable');

for(var j=0;j<tableID.length;j++) {
    $('<td>' + Result[i][tableID[j]] + '</td>').appendTo(tr);
}
0

You are appending your data after the table, not after the last row, see Add table row in jQuery for more information how to add a row after the last row.

Community
  • 1
  • 1
trizz
  • 1,447
  • 12
  • 27
0

You don't append <td> elements to the table, you have to append them to the row you just added.

for(var i=0;i<Result.length;i++){
    var row = $('<tr>').appendTo('#resultstable');

    for(var j=0;j<tableID.length;j++){
        $('<td>' + Result[i][tableID[j]] + '</td>').appendTo(row);
    }
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

Your code should be well

for(var i=0;i<Result.length;i++){
  var tr =  $('<tr>').appendTo('#resultstable');
  for(var j=0;j<tableID.length;j++){
    $('<td>' + Result[i][tableID[j]] + '</td>').appendTo(tr );
  }
}
Paulo Lima
  • 1,238
  • 8
  • 8