Dynamically Add & Remove Table Rows



DEMO

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>How to add & remove table rows</title>
    <link   href="https://fonts.googleapis.com/css2?family=K2D:wght@100;400&display=swap"  rel="stylesheet"  />

    <style>
      body {
        font-family: "Roboto", sans-serif;
      }
      h1 {
        text-align: center;
      }
      table,
      form {
        width: 500px;
        margin: 20px auto;
      }
      table {
        border-collapse: collapse;
        text-align: center;
      }
      table td,
      table th {
        border: solid 1px black;
      }
      label,
      input {
        display: block;
        margin: 10px 0;
        font-size: 20px;
      }
      button {
        display: block;
      }
    </style>
  </head>
  <body>
    <h1>Dynamically Add & Remove Table Rows</h1>
    <form>
      <div class="input-row">
        <label for="name">Fullname</label>
        <input type="text" name="name" id="name" />
      </div>
      <div class="input-row">
        <label for="email">Email</label>
        <input type="text" name="email" id="email" />
      </div>
      <div class="input-row">
        <label for="address">Address</label>
        <input type="text" name="address" id="address" />
      </div>
      <div class="input-row">
        <label for="phone">Phone</label>
        <input type="text" name="phone" id="phone" />
      </div>
      <button>Submit</button>
    </form>
    <table>
      <thead>
        <tr>
          <th>Fullname</th>
          <th>Email</th>
          <th>Address</th>
          <th>Phone</th>
          <th>Action</th>
        </tr>
      </thead>
      <tbody></tbody>
    </table>
    <script>
      const formEl = document.querySelector("form");
      const tbodyEl = document.querySelector("tbody");
      const tableEl = document.querySelector("table");
      function onAddWebsite(e) {
        e.preventDefault();
        const fname = document.getElementById("name").value;
        const email = document.getElementById("email").value;
        const address = document.getElementById("address").value;
        const phone = document.getElementById("phone").value;
        tbodyEl.innerHTML += `
            <tr>
                <td>${fname}</td>
                <td>${email}</td>
                <td>${address}</td>
                <td>${phone}</td>
                <td><button class="deleteBtn">Delete</button></td>
            </tr>
        `;
      }

      function onDeleteRow(e) {
        if (!e.target.classList.contains("deleteBtn")) {
          return;
        }
        const btn = e.target;
        btn.closest("tr").remove();
      }

      formEl.addEventListener("submit", onAddWebsite);
      tableEl.addEventListener("click", onDeleteRow);
      
    </script>
  </body>
</html>

Ref: 
แสดงความคิดเห็น (0)
ใหม่กว่า เก่ากว่า