Search code examples
javascripthtmlcssdynamic-tables

Dynamically Update a Table in Javascript


I have a table here and each cell within the table is an input field. I have a function to add a new row dynamically to the bottom of the table, but when I add the new row to the table it deletes the content of the input fields in the process. What's the proper way to do this? I'd like to be able to fill out the table dynamically and add rows as needed without deleting the contents of each cell in the process. Thanks in advance!

document.getElementById("btnAddItem").addEventListener("click", function () {
  numItems++;
  let template = `
  <tr>
  <td>
  <input type="text" id="itemDescription${numItems}" placeholder="Item" />
  </td>
  <td>
  <input type="text" id="itemValue${numItems}" placeholder="Value" />
  </td>
  </tr>
  `;

  table.innerHTML += template;
});

Solution

  • You could try something like this

    const table = document.getElementById('Table');
    let numItems = 1;
    document.getElementById("btnAddItem").addEventListener("click", function () {
        numItems++;
        const row = document.createElement('tr');
        row.innerHTML = `
      <td>
      <input type="text" id="itemDescription${numItems}" placeholder="Item" />
      </td>
      <td>
      <input type="text" id="itemValue${numItems}" placeholder="Value" />
      </td>`;
      // You could also do the same for the cells and inputs
        table.appendChild(row);
    });
    <button id="btnAddItem">Add</button>
    <table id="Table">
    </table>