JavaScript Form submit Event: The Complete Guide

JavaScript has many events that help us interact with web elements. One of these important events is the submit event. This guide will explain everything you need to know about the submit event. We’ll cover what it is, why it’s useful, where to use it, how to implement it, and when it comes into play. Let’s dive in!

What is the submit Event?

The submit event in JavaScript is fired when a form is submitted. It is commonly used to execute JavaScript code right before the form data is sent to the server. This event allows you to validate form data, prevent form submission, or modify the form data before it is sent.

Why Use the submit Event?

Using the submit event is beneficial because it lets you control what happens when a form is submitted. You can validate the form data, show error messages, prevent the form from submitting if the data is invalid, and even send the data using AJAX without reloading the page.

Where Can You Use the submit Event?

You can use the submit event on any HTML form element. This event is particularly useful in applications that require form validation, dynamic form submission, or custom handling of form data before it is sent to the server.

How to Use the submit Event

Let’s dive into some examples to see how the submit event works in different scenarios.

Basic Example

Here’s a simple example to show how the submit event works with a form element.

HTML
<form id="myForm">
  <label for="name">Name:</label>
  <input type="text" id="name" name="name" />
  <button type="submit">Submit</button>
</form>

<p id="status">Status: Waiting for submission ⏳</p>

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

  form.addEventListener("submit", (event) => {
    event.preventDefault();
    const name = form.elements["name"].value;
    status.textContent = `Status: Form submitted with name: ${name} πŸŽ‰`;
  });
</script>

In this example, when the form is submitted, the status message updates, and the form submission is prevented.

Example with Validation

Let’s see how the submit event works with form validation.

HTML
<form id="validationForm">
  <label for="email">Email:</label>
  <input type="email" id="email" name="email" />
  <button type="submit">Submit</button>
</form>

<p id="validationStatus">Status: Waiting for submission ⏳</p>

<script>
  const form = document.getElementById("validationForm");
  const status = document.getElementById("validationStatus");

  form.addEventListener("submit", (event) => {
    event.preventDefault();
    const email = form.elements["email"].value;
    if (!email.includes("@")) {
      status.textContent = "Status: Invalid email address ❌";
    } else {
      status.textContent = `Status: Form submitted with email: ${email} πŸŽ‰`;
    }
  });
</script>

In this example, the form is only submitted if the email address is valid.

Example with AJAX Submission

Let’s see how the submit event works with AJAX submission.

HTML
<form id="ajaxForm">
  <label for="username">Username:</label>
  <input type="text" id="username" name="username" />
  <button type="submit">Submit</button>
</form>

<p id="ajaxStatus">Status: Waiting for submission ⏳</p>

<script>
  const form = document.getElementById("ajaxForm");
  const status = document.getElementById("ajaxStatus");

  form.addEventListener("submit", (event) => {
    event.preventDefault();
    const username = form.elements["username"].value;

    const xhr = new XMLHttpRequest();
    xhr.open("POST", "https://jsonplaceholder.typicode.com/posts", true);
    xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");

    xhr.onload = function () {
      if (xhr.status === 201) {
        status.textContent = `Status: Form submitted with username: ${username} πŸŽ‰`;
      } else {
        status.textContent = "Status: Submission failed ❌";
      }
    };

    xhr.send(JSON.stringify({ username }));
  });
</script>

In this example, the form data is submitted using AJAX, and the page does not reload.

When to Use the submit Event

The submit event is particularly useful in scenarios where:

  • You need to validate form data before it is sent to the server.
  • You want to provide feedback to users about the form submission process.
  • You handle form data dynamically and want to send it using AJAX without reloading the page.

Comparing submit with Other Form Events

To understand the submit event better, let’s compare it with other common form events.

EventDescriptionExample Usage
submitFired when a form is submittedValidate form data and send it using AJAX
resetFired when a form is resetReset form fields and status messages
inputFired whenever the value of an input changesProvide live feedback on form fields
changeFired when the value of an input changes and loses focusValidate field values after changes

Code Examples of Different Events

Here’s how you can use some of these events in your code:

HTML
<form id="exampleForm">
  <label for="exampleInput">Input:</label>
  <input type="text" id="exampleInput" name="exampleInput" />
  <button type="submit">Submit</button>
  <button type="reset">Reset</button>
</form>

<p id="exampleStatus">Status: Waiting for interaction ⏳</p>

<script>
  const form = document.getElementById("exampleForm");
  const status = document.getElementById("exampleStatus");
  const input = document.getElementById("exampleInput");

  form.addEventListener("submit", (event) => {
    event.preventDefault();
    status.textContent = `Status: Form submitted with input: ${input.value} πŸŽ‰`;
  });

  form.addEventListener("reset", () => {
    status.textContent = "Status: Form reset πŸ”„";
  });

  input.addEventListener("input", () => {
    status.textContent = `Status: Input changed to: ${input.value} ✍️`;
  });

  input.addEventListener("change", () => {
    status.textContent = `Status: Input finalized as: ${input.value} βœ”οΈ`;
  });
</script>

Conclusion

The submit event in JavaScript is a powerful tool for handling form submissions. By understanding and using this event, you can create more interactive and user-friendly web applications. Whether you are validating form data, preventing form submission, or sending data using AJAX, the submit event helps you ensure that your forms work smoothly and effectively.

Summary

  • What: The submit event fires when a form is submitted.
  • Why: It helps in controlling form submission, validating data, and sending data using AJAX.
  • Where: Use it on any HTML form element.
  • How: By adding an event listener for submit and handling the form data accordingly.
  • When: Use it whenever you need to manage form submissions, validate data, or send data without reloading the page.

Feel free to use the examples provided and modify them to suit your needs. Happy coding! πŸŽ‰

What are JavaScript Browser Events?

JavaScript browser events are key to creating interactive web applications. These events are actions or occurrences detected by the browser, such as user interactions, document changes, or window modifications. By responding to events like clicks, key presses, and form submissions, developers can enhance user experience and functionality.

This comprehensive list of JavaScript browser events is a valuable reference for developers. It covers a wide range of events, from mouse and keyboard actions to document and window changes. Understanding and handling these events is essential for building responsive and engaging web applications, ensuring a seamless and intuitive user experience.

See List of all JavaScript Browser Events – Cheat Sheet

Leave a Reply