Skip to content
Advertisement

Make table which have cells 10×10 and every cells have inside number from 1 to 100

Need to make table which have numbers from 1 to 100, and it should be 10×10 cells. I make cells 10×10 but result fill every grid line from 1 to 10, how to make every line like that 1 to 10, 11 to 20 and to 100 like that ? Thank you for attention to my problem.

function generate_table() {
  const tbl = document.createElement("table");
  const tblBody = document.createElement("tbody");
  for (let i = 1; i < 11; i++) {
    const row = document.createElement("tr");
    for (let j = 0; j < 10; j++) {
      const cell = document.createElement("td");
      const cellText = document.createTextNode(i);
      cell.appendChild(cellText);
      row.appendChild(cell);
    }
    tblBody.appendChild(row);
  }
  tbl.appendChild(tblBody);
  document.body.appendChild(tbl);
  tbl.setAttribute("border", "1");
}
<form action="#">
  <input type="button" value="Generate a table" onclick="generate_table()">
</form>

Advertisement

Answer

function generate_table() {
  const tbl = document.createElement("table");
  const tblBody = document.createElement("tbody");
  for (let y = 0; y < 10; y++) {
    const row = document.createElement("tr");
    for (let x = 0; x < 10; x++) {
      const cell = document.createElement("td");
      const cellText = document.createTextNode((x + 10 * y) + 1);
      cell.appendChild(cellText);
      row.appendChild(cell);
    }
    tblBody.appendChild(row);
  }
  tbl.appendChild(tblBody);
  document.body.appendChild(tbl);
  tbl.setAttribute("border", "1");
}
<form action="#">
  <input type="button" value="Generate a table" onclick="generate_table()">
</form>
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement