简体   繁体   中英

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM