HomeJAVASCRIPTHow to handle form submission using JS?

How to handle form submission using JS?

To handle form submission using JavaScript, you usually attach an event listener to the form’s submit event, then process the data or prevent the default submission if needed.

Here’s a step-by-step guide with examples:


✅ 1. Basic Example (Prevent Page Reload)

<form id="myForm">
  <input type="text" name="username" placeholder="Enter username" required>
  <input type="email" name="email" placeholder="Enter email" required>
  <button type="submit">Submit</button>
</form>

<script>
  const form = document.getElementById("myForm");

  form.addEventListener("submit", function(event) {
    event.preventDefault(); // prevent page reload (default form behavior)

    // Get form data
    const formData = new FormData(form);
    const username = formData.get("username");
    const email = formData.get("email");

    console.log("Username:", username);
    console.log("Email:", email);

    // You can now send data via fetch or process it further
  });
</script>

✅ 2. Sending Data with fetch (AJAX Style)

<form id="loginForm">
  <input type="text" name="username" placeholder="Username" required>
  <input type="password" name="password" placeholder="Password" required>
  <button type="submit">Login</button>
</form>

<script>
  const loginForm = document.getElementById("loginForm");

  loginForm.addEventListener("submit", async function(e) {
    e.preventDefault();

    const formData = new FormData(loginForm);

    const response = await fetch("/submit", {
      method: "POST",
      body: formData
    });

    const result = await response.json();
    console.log("Server Response:", result);
  });
</script>

✅ 3. Accessing Input Values Directly

form.addEventListener("submit", function(e) {
  e.preventDefault();
  
  const username = document.querySelector("input[name='username']").value;
  const email = document.querySelector("input[name='email']").value;

  console.log(username, email);
});

Key Points:

  • submit event is fired when the form is submitted.
  • Use event.preventDefault() to stop the page from reloading.
  • Use FormData for easy access to all input values.
  • Use fetch or AJAX to send data without refreshing the page.
  • Always validate inputs before sending data.

Share: 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *