bilal1409 bilal1409 - 5 months ago 11
HTML Question

Add rows to table dynamically in HTML

How to add new rows to HTML table automatically by getting the data of these rows from a web page.

<table class="sortable">
<thead>
<tr>
<th>Foldername</th>
<th>Subfolder</th>
</tr>
</thead>
<tbody>
<tr class='$class'>
<td><span id="albumname"></span></td>
<td><span id="subdirname"></span></td>
</tr>
</tbody>
</table>


Foldername and Subfolder are the headings and no need to change them, but albumname and subdirname must changed by their corresponding values each row.

I get the data using websocket:

$.get("http://localhost:8040/api/album", function (data) {
console.log("data: ", data);
var i;
var j;
console.log(i);
for (i = 0; i < data.length; i++) {
console.log("start for loop");
var albname = data[i].Name;
console.log("albname: ", albname);
$("#albumname").text(albname);
var subalbum = data[i].SubAlbums
for (j = 0; j < subalbum.length; j++) {
var subname = data[i].SubAlbums[j];
console.log("SubName: ", subname);
$("#subdirname").text(subname);
}
}
});

Answer

Add a class to <body> like this,

<tbody class="tableBody">

</tbody>

And update your jQuery code as follow, assuming there would be multiple subdirename for each album.

$.get("http://localhost:8040/api/album", function (data) {
      var i;
      var j;
      $('.tableBody').html('');
      for (i = 0; i < data.length; i++) {
        console.log("start for loop");
        var albname = data[i].Name;

        var bodyTr=$('<tr>');

        var albumNameTd=$('<td>');
        albumNameTd.text(albname);

        var subDirNameTd=$('<td>');
        var subDirHtml="";

        var subalbum = data[i].SubAlbums;

        for (j = 0; j < subalbum.length; j++) {
          var subname = data[i].SubAlbums[j];
          subDirHtml+=subname;
          if(j!=subalbum.length-1) {
                subDirHtml+="<br>";
          }
        }
        subDirNameTd.html(subDirHtml);
        bodyTr.append(albumNameTd);
        bodyTr.append(subDirNameTd);
        $('.tableBody').append(bodyTr);
      }
});
Comments