JavaScript Form reset Event: The Complete Guide

JavaScript provides us with many events that help make our web pages interactive and dynamic. One of these useful events is the reset event. This guide will explain everything you need to know about the reset event. We will 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 reset Event?

The reset event in JavaScript is fired when a form is reset. This event occurs when the reset button of a form is clicked or when the form.reset() method is called. The reset event allows you to run JavaScript code whenever a form is reset, letting you customize the behavior of form resets.

Why Use the reset Event?

Using the reset event is beneficial because it lets you control what happens when a form is reset. You can use it to clear form fields, reset status messages, or perform other actions that should occur when a form is reset. This helps in maintaining a clean and predictable user interface.

Where Can You Use the reset Event?

You can use the reset event on any HTML form element. This event is particularly useful in applications that require custom handling of form resets to ensure a consistent and user-friendly experience.

How to Use the reset Event

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

Basic Example

Here’s a simple example to show how the reset 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>
  <button type="reset">Reset</button>
</form>

<p id="status">Status: Fill out the form ⏳</p>

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

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

In this example, when the form is reset, the status message updates to indicate the reset.

Example with Form Validation

Let’s see how the reset event works with form validation and status messages.

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

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

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

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

  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 status message updates to indicate the reset, and the form is validated before submission.

Example with AJAX and Form Reset

Let’s see how the reset event works with AJAX form submission and reset handling.

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

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

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

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

  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 form is reset to clear the fields and update the status message.

When to Use the reset Event

The reset event is particularly useful in scenarios where:

  • You need to handle form resets to clear fields and update status messages.
  • You want to provide feedback to users when a form is reset.
  • You manage form data dynamically and need to ensure a consistent user experience after resets.

Comparing reset with Other Form Events

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

EventDescriptionExample Usage
resetFired when a form is resetClear form fields and update status messages
submitFired when a form is submittedValidate form data and send it using AJAX
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("reset", () => {
    status.textContent = "Status: Form reset πŸ”„";
  });

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

  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 reset event in JavaScript is a powerful tool for handling form resets. By understanding and using this event, you can create more interactive and user-friendly web applications. Whether you are clearing form fields, updating status messages, or managing form data dynamically, the reset event helps you ensure that your forms work smoothly and effectively.

Summary

  • What: The reset event fires when a form is reset.
  • Why: It helps in handling form resets, clearing fields, and updating status messages.
  • Where: Use it on any HTML form element.
  • How: By adding an event listener for reset and handling the form reset accordingly.
  • When: Use it whenever you need to manage form resets and provide feedback to users.

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

  • Document events:
    • ended
    • error
    • loadeddata
    • loadedmetadata
    • loadstart
    • pause
    • play
    • playing
    • progress
    • ratechange
    • seeked
    • seeking
    • stalled
    • suspend
    • timeupdate
    • volumechange
    • waiting
    • emptied
    • durationchange
    • cuechange
    • change
    • canplaythrough
    • canplay
    • abort
    • DOMContentLoaded
  • Window events:
    • afterprint
    • beforeprint
    • beforeunload
    • error
    • hashchange
    • load
    • message
    • offline
    • online
    • pagehide
    • pageshow
    • popstate
    • resize
    • scroll
    • storage
    • unload
  • Form events:
    • submit
    • select
    • reset
    • invalid
    • input
    • focus
    • change
    • blur
  • Keyboard events:
    • keyup
    • keypress
    • keydown
  • Mouse events:
    • wheel
    • mouseup
    • mouseover
    • mouseout
    • mousemove
    • mouseleave
    • mouseenter
    • mousedown
    • dblclick
    • contextmenu
    • click

Leave a Reply