Handling Form Events in JavaScript: Examples and Best Practices


Form events in JavaScript are events that are triggered when a user interacts with a form on a web page. These events allow you to capture and respond to user actions, such as submitting a form, entering data into form fields, or resetting a form.

Here are some commonly used form events in JavaScript:

  1. submit: This event is triggered when a form is submitted, either by clicking a submit button or pressing the Enter key within a form field. You can use this event to perform form validation, submit form data to a server, or handle other form-related tasks.
  2. input: This event is triggered when the value of a form field is changed by the user. This includes events such as typing in a text input, selecting an option in a dropdown, or changing the value of a checkbox or radio button. You can use this event to dynamically update the form or perform real-time validation.
  3. change: This event is triggered when the value of a form field is changed and the field loses focus. This includes events such as selecting an option in a dropdown or changing the value of a checkbox or radio button. You can use this event to capture changes made by the user and perform tasks accordingly.
  4. reset: This event is triggered when a form is reset, either by clicking a reset button or programmatically resetting the form using JavaScript. You can use this event to perform cleanup tasks or reset the form's state.
  5. focus : The focus event is triggered when an element, such as a form field, receives focus. This typically occurs when the user clicks or tabs into an input field.
  6. checked : The checked property is used to determine whether a checkbox or a radio button is checked or not. It is a boolean property that returns true if the element is checked, and false if it is not checked.
  7. blur : The checked property is used to determine whether a checkbox or a radio button is checked or not. It is a boolean property that returns true if the element is checked, and false if it is not checked.

To handle form events in JavaScript, you can use event listeners or event handlers. Event listeners are functions that are registered to listen for specific events on specific DOM elements, while event handlers are functions that are directly assigned to handle specific events. These functions can be written in JavaScript and can manipulate the DOM, validate form data, and perform other actions based on the user's interactions with the form.

Form events in JavaScript are an essential part of building interactive and dynamic web forms that provide a smooth user experience. Properly handling form events can help you create robust and user-friendly web forms that are responsive to user input and behavior.

Example

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="icon" type="image/ico" href="logo.png" />
    <title>Document</title>
    <style>
      @import url("https://fonts.googleapis.com/css2?family=Lobster&family=Poppins:wght@100;200;300;400;500;600;700;800&display=swap");
      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
        font-family: "Poppins", sans-serif;
      }
      body {
        width: 100vw;
        height: 100vh;
        background-color: palegreen;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 12px;
      }
      h1 {
        font-weight: 500;
        text-transform: uppercase;
        font-size: 14px;
      }
      form {
        width: 300px;
        background-color: #fff;
        padding: 10px;
      }
      .form-group {
        margin-bottom: 10px;
      }
      .form-group > label {
        display: block;
        padding: 3px 0;
      }
      input[type="text"],
      input[type="email"],
      select {
        width: 100%;
        outline: none;
        font-size: 12px;
      }
      fieldset {
        border: none;
      }
      button {
        width: 100px;
        border: none;
        background-color: #222;
        color: #fff;
        padding: 2px 10px;
      }

      form .form-group:last-of-type {
        margin-top: 10px;
      }
    </style>
  </head>
  <body>
    <form action="#" autocomplete="off">
      <h1>Form Events in JavaScript</h1>
      <div class="form-group">
        <label for="username">User Name</label>
        <input type="text" id="username" />
      </div>
      <div class="form-group">
        <label for="email">Email</label>
        <input type="email" id="email" />
      </div>
      <div class="form-group">
        <label for="course">Course Name</label>
        <select id="course">
          <option value="">Select Course</option>
          <option value="C">C</option>
          <option value="C++">C++</option>
          <option value="Java">Java</option>
        </select>
      </div>
      <div class="form-group">
        <fieldset>
          <legend>Gender</legend>
          <label><input type="radio" name="gender" value="male" /> Male</label>
          <label><input type="radio" name="gender" value="female" />Female</label>
        </fieldset>
      </div>
      <input type="checkbox" id="agree" />
      <label for="agree">I Agree all Condition</label>
      <div class="form-group">
        <button type="submit">Submit</button>
        <button type="reset">Reset</button>
      </div>
    </form>
    <script src="115_form_events.js"></script>
  </body>
</html>

script.js

/*
  Form Events in JavaScript
      submit
      reset
      change

      checked
      blur
      focus
      input
     
*/

const form = document.querySelector("form");
const username = document.querySelector("#username");
const email = document.querySelector("#email");
const course = document.querySelector("#course");
const checkbox = document.querySelector("#agree");
const radios = document.querySelectorAll('input[name="gender"]');

form.addEventListener("submit", function (e) {
  e.preventDefault();
  console.log("Form Submitted");
  console.log("User Name : ", username.value);
  console.log("Email     : ", email.value);

  let selectedGender = "";
  radios.forEach((radio) => {
    if (radio.checked) {
      selectedGender = radio.value;
    }
  });
  console.log("Gender :", selectedGender);
});

course.addEventListener("change", function (e) {
  const selectedCourse = e.target.value;
  console.log("Selected Course     : ", selectedCourse);
});

form.addEventListener("reset", function (e) {
  console.log("Reset or Clear Form Data");
});

checkbox.addEventListener("change", function (e) {
  if (e.target.checked) {
    console.log("Checkbox is checked.");
  } else {
    console.log("Checkbox is unchecked.");
  }
});

username.addEventListener("input", function (e) {
  console.log("Username input changed:", e.target.value);
});

username.addEventListener("focus", function (e) {
  username.style.borderColor = "orange";
});

username.addEventListener("blur", function (e) {
  username.style.borderColor = "black";
});

The provided code demonstrates the use of various form events in JavaScript, along with some related event listeners and event handling functions. Here's a brief explanation of the code:

  • Form submit event: The submit event is triggered when the form is submitted. In the code, an event listener is added to the form element, and when the form is submitted, the event handling function prevents the default form submission behavior using e.preventDefault(), and logs the form data including the values of the username, email, and gender fields to the console.
  • Form reset event: The reset event is triggered when the form is reset. In the code, an event listener is added to the form element, and when the form is reset, the event handling function logs a message to the console indicating that the form data has been cleared.
  • change event: The change event is triggered when the value of a form field, such as a select element, is changed. In the code, an event listener is added to the course select element, and when the selected course is changed, the event handling function logs the selected course value to the console.
  • checked property: The checked property is used to determine whether a checkbox or a radio button is checked or not. In the code, an event listener is added to the checkbox element, and when the checkbox is checked or unchecked, the event handling function logs a message to the console accordingly.
  • input event: The input event is triggered when the value of an input field, such as a text input or textarea, is changed. In the code, an event listener is added to the username input element, and when the username input is changed, the event handling function logs the changed value to the console.
  • focus and blur events: The focus event is triggered when an element receives focus, and the blur event is triggered when an element loses focus. In the code, event listeners are added to the username input element, and when the input element receives focus, the border color is changed to orange, and when it loses focus, the border color is changed back to black.

In summary, the provided code demonstrates the use of form events in JavaScript, including submit, reset, change, checked, input, focus, and blur events, along with their corresponding event listeners and event handling functions. These events and event handling functions can be used to create dynamic and interactive forms in web applications.

List of Programs


JS Practical Questions & Answers


JS Practical Project