Create a html table where inputs are inside

I have the following html table:

<table>
    <tr>
      <td> <input> </td>
      <td> <input> </td>
      <td> <input> </td>
    </tr>
    <tr>
      <td> <input> </td>
      <td> <input> </td>
      <td> <input> </td>
    </tr>
    <tr>
      <td> <input> </td>
      <td> <input> </td>
      <td> <input> </td>
    </tr>
  </table>

Instead, I would like to create this table only with javascript. I have read the following post. However, I would like that inside every <td> there is an <input> (as shown on the code provided). Any guidance or help would be appreciated. Thanks!

Answer

I found the answer:

let table = document.querySelector('table');

function generateTable(table) {
  for (let i = 0; i < 5; i++) {
    let row = table.insertRow();
    for (let a = 0; a < 5; a++) {
      let cell = row.insertCell();
      let inputCell = document.createElement("INPUT");
      cell.appendChild(inputCell);
    }
  }
}

generateTable(table)
<table> </table>

Leave a Reply

Your email address will not be published. Required fields are marked *