Home > Blockchain >  HTML table not displaying
HTML table not displaying

Time:12-18

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

CodePudding user response:

@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;
  }
});

CodePudding user response:

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

  ratings = JSON.parse(sessionStorage.ratings); // RATINGS IS OBJECT HERE
  for (let i = 0; i < ratings.length; i  ) { // ratings.length will not work as it's not an array
      let tr = "<tr>";

      /* Verification to add the last decimal 0 */
      if (ratings[i].value.toString().substring(ratings[i].value.toString().indexOf('.'), ratings[i].value.toString().length) < 2) 
          ratings[i].value  = "0";

      /* Must not forget the $ sign */
      tr  = "<td>"   ratings[i].key.toString()   "</td>"   "<td>"   ratings[i].value.toString()   "</td></tr>";

      /* We add the table row to the table body */
      tbody.innerHTML  = tr;
  }
});

Please see the comments added at line 4 and 5

  • Related