JSFiddle - React, Tailwind, and code Playground

by Prathameshsb

HTML

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Form and Table Example</title>
  </head>
  <body>
    <h1>Form and Table Example</h1>

    <!-- Form to collect user data -->
    <form id="userDataForm">
      <label for="name">Name:</label>
      <input type="text" id="name" required />
      <br /><br />
      <label for="email">Email:</label>
      <input type="email" id="email" required />
      <br /><br />
      <label for="number">Number:</label>
      <input type="tel" id="number" required />
      <br /><br />
      <button type="submit">Submit</button>
    </form>

    <!-- Table to display user data -->
    <table id="userDataTable">
      <thead>
        <tr>
          <th>Name</th>
          <th>Email</th>
          <th>Number</th>
        </tr>
      </thead>
      <tbody>
        <!-- User data will be displayed here -->
      </tbody>
    </table>
  </body>
</html>

CSS

/* Add some basic CSS for styling */
      body {
        font-family: Arial, sans-serif;
        text-align: center;
      }
      table {
        width: 100%;
        border-collapse: collapse;
        margin-top: 20px;
      }
      table,
      th,
      td {
        border: 1px solid #ccc;
      }
      th,
      td {
        padding: 10px;
      }

JavaScript

// Array to store user data
      const userData = [];

      // Get the form element
      const userDataForm = document.getElementById("userDataForm");

      // Add a submit event listener to the form
      userDataForm.addEventListener("submit", function (event) {
        event.preventDefault(); // Prevent the default form submission

        // Get values from the form
        const name = document.getElementById("name").value;
        const email = document.getElementById("email").value;
        const number = document.getElementById("number").value;

        // Add data to the array
        userData.push({ name, email, number });

        // Clear form fields
        userDataForm.reset();

        // Display data in the table
        displayDataInTable();
      });

      function displayDataInTable() {
        const tableBody = document.querySelector("#userDataTable tbody");
        tableBody.innerHTML = "";

        userData.forEach((user) => {
          const row = tableBody.insertRow();
          const nameCell = row.insertCell(0);
          const emailCell = row.insertCell(1);
          const numberCell = row.insertCell(2);

          nameCell.textContent = user.name;
          emailCell.textContent = user.email;
          numberCell.textContent = user.number;
        });
      }