Skip to content

Form events in JavaScript

  • by

In JavaScript, form events are events that are triggered by HTML form elements, such as input fields, checkboxes, select dropdowns, and buttons, when certain actions or interactions occur.

These events allow you to detect and respond to user interactions with forms, enabling you to create dynamic and interactive web applications.

Some commonly used form events in JavaScript include:

  1. submit: The submit event is triggered when the user attempts to submit a form, typically by clicking a submit button or pressing Enter within an input field. It is commonly used to perform form validation, handle form data, and prevent the default form submission behavior.
  2. reset: The reset event occurs when the user clicks a form’s reset button, which restores the form’s default values. It can be used to perform actions such as confirmation prompts or resetting additional state variables.
  3. change: The change event is fired when the value of an input field, select dropdown, or checkbox is changed and then loses focus. It is often used to track and respond to changes made by the user in form inputs.
  4. focus: The focus event is triggered when an element receives focus, typically when a user clicks or tabs into an input field. It can be used to perform actions such as displaying additional information or highlighting the focused element.
  5. blur: The blur event occurs when an element loses focus, such as when a user clicks outside an input field after interacting with it. It can be used to perform actions or validations when an element is no longer in focus.
  6. input: The input event is fired whenever the value of an input field changes, including when the user types, deletes, or pastes text. It is commonly used to capture real-time changes in form inputs and update the UI accordingly.

Here’s a syntax overview for attaching event listeners to form elements in JavaScript:

// Get a reference to the form element
const form = document.getElementById('myForm');

// Add an event listener for the 'submit' event
form.addEventListener('submit', function(event) {
  // Prevent the default form submission behavior
  event.preventDefault();

  // Perform form validation or other actions
  // ...
});

// Add an event listener for the 'reset' event
form.addEventListener('reset', function(event) {
  // Perform actions when the form is reset
  // ...
});

// Get a reference to an input element within the form
const input = document.getElementById('myInput');

// Add an event listener for a specific event on the input element
input.addEventListener('change', function(event) {
  // Handle the change event for the input element
  // ...
});

In this syntax example, the addEventListener method is used to attach event listeners to form elements. The first argument is the name of the event you want to listen for, such as 'submit', 'reset', 'change', 'input', 'focus', 'blur', etc.

Form events in JavaScript example

Simple example code.

<!DOCTYPE html>
<html>
<head>
  <title>Form Events Example</title>
</head>
<body>
  <form id="myForm">
    <label for="name">Name:</label>
    <input type="text" id="name" />

    <label for="email">Email:</label>
    <input type="email" id="email" />

    <label for="message">Message:</label>
    <textarea id="message"></textarea>

    <input type="submit" value="Submit" />
    <input type="reset" value="Reset" />
  </form>

  <script>
    const form = document.getElementById('myForm');
    const nameInput = document.getElementById('name');
    const emailInput = document.getElementById('email');
    const messageInput = document.getElementById('message');

    form.addEventListener('submit', function(event) {
      event.preventDefault(); // Prevent form submission
      console.log('Form submitted');

      // Access form input values
      const nameValue = nameInput.value;
      const emailValue = emailInput.value;
      const messageValue = messageInput.value;

      // Perform form validation
      if (nameValue.trim() === '') {
        console.log('Name is required');
        return;
      }

      if (emailValue.trim() === '') {
        console.log('Email is required');
        return;
      }

      if (messageValue.trim() === '') {
        console.log('Message is required');
        return;
      }

      // Submit the form or perform further actions
      console.log('Form data:', { name: nameValue, email: emailValue, message: messageValue });
      form.reset();
    });

    form.addEventListener('reset', function(event) {
      console.log('Form reset');
    });
  </script>
</body>
</html>

Output:

Form events in JavaScript

In this example, we have a simple HTML form with inputs for name, email, and message, as well as a submit button and a reset button. We attach event listeners to the form element to handle the submit and reset events.

When the user submits the form by clicking the submit button, the submit event listener is triggered. We use event.preventDefault() to prevent the default form submission behavior and perform our own handling.

Comment if you have any doubts or suggestions on this Js event topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading