0

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

1 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.