Search code examples
javascripthtmlobjecthtml-table

HTML table not displaying


I wanted to display a javascript object variable as a HTML table when a button with the id "stop" is pressed. I took some of my code for this problem from another question, however for some reason the browser doesn't even render the table.

Html

<table id="tbody"></table>

JavaScript

stop.addEventListener("click", () => {
  container.style.display = "none";
  stop.style.display = "none";
  tbody.style.display = "block";


  ratings = JSON.parse(sessionStorage.ratings);
  for (let i = 0; i < ratings.length; i++) {
      let tr = "<tr>";
      tr += "<td>" + ratings[i].key.toString() + "</td>" + "<td>" + ratings[i].value.toString() + "</td></tr>";
      tbody.innerHTML += tr;
  }
});

I even specifically mention the display in my javascript file, as you can see:

 tbody.style.display = "block";

If needed, you can find the full code here


Solution

  • @Ashish Kumar was right, the rating variable was an object. The TypeError (that came later) occurred because I was indexing the object like an array. Fixed that through the following edit in the event listener function :

    stop.addEventListener("click", () => {
      container.style.display = "none";
      stop.style.display = "none";
      tbody.style.display = "block";
    
      ratings = JSON.parse(sessionStorage.ratings);
      // console.log(ratings);
      for (let i = 0; i < Object.keys(ratings).length; i++) {
          let tr = "<tr>";
          tr += "<td>" + Object.keys(ratings)[i] + "</td>" + "<td>" + Object.values(ratings)[i] + "</td></tr>";
          tbody.innerHTML += tr;
      }
    });