JSON table data not showing after adding to innerHTML

Viewed 218

I'm trying to build a simple table using JSON data from a google sheets URL. I have it working in another instance, using the same JSON data to populate divs in a grid.

But when I apply the same principle to building a table, I can only get the first row to appear – see here:

var url = '[json feed]';

$.getJSON(url, function appendData(data) {

  var tableContent = document.getElementById("content");

  var entries = data.feed.entry;
  console.log(entries);

  for (var i = 0; i < entries.length; i++) {

    var tableRow = document.createElement("tr");

    tableRow.innerHTML = '<td>' + entries[i].gsx$position.$t; + '</td><td>' + entries[i].gsx$team.$t; + '</td><td>' + entries[i].gsx$weeklyscore.$t; + '</td><td>' + entries[i].gsx$totals.$t; + '</td>';

    tableContent.appendChild(tableRow);

  };
});
table {
  border: 1px solid black;
}

td {
  border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <table>
    <tbody id="content">
      <tr>
        <th>Position</th>
        <th>Team</th>
        <th>Weekly Score</th>
        <th>Totals</th>
      </tr>

    </tbody>
  </table>
</div>

I've been over and over it, and I cannot figure out how to get to the rest of the JSON data between the <td> tags after tableRow.innerHTML = to populate the rest of the table.

I'm sure it's something simple I'm not getting, but any help would be appreciated! Thanks

2 Answers

Please try this,

var tableRow = document.createElement("tr");
              
var str = '<td>' + entries[i].gsx$position.$t + '</td><td>' + entries[i].gsx$team.$t + '</td><td>' + entries[i].gsx$weeklyscore.$t + '</td><td>' + entries[i].gsx$totals.$t + '</td>';
tableRow.innerHTML = str;
tableContent.appendChild(tableRow);

There was an extra ; in all "$t" like this "$t;" in your code.

Set the innerHTML of your table's tbody--not row.

Note: Using innerHTML to do this is not something I recommend, but here's an example regardless.

document.getElementById("bn_insert_body").addEventListener("click", e => {

  const rows = `<tr><td>Body Column 1</td><td>Body Column 2</td><td>Body Column 3</td></tr>
  <tr><td>Body Column 1</td><td>Body Column 2</td><td>Body Column 3</td></tr>`;
  
  document.querySelector("#my_table tbody").innerHTML = rows;
  
});
<table id="my_table">
<thead>
  <tr>
    <th>Column 1</th>
    <th>Column 2</th>
    <th>Column 3</th>
  </tr>
</thead>
<tbody>
</tbody>
</table>

<button type="button" id="bn_insert_body">Insert Data</button>

Related