Form Events

Frontend SELF EN
Level 9 , Lesson 3
Available

9.1 Main Form Events

To make forms functional, you gotta understand and manage the events that happen when users interact with form elements. Let's break down the main events in HTML forms, handling them with JavaScript, and some examples of how to use them.

In HTML, forms can trigger various events when users interact with elements like input fields, buttons, checkboxes, and radio buttons. The main form events include:

  • submit — form submission event
  • reset — form reset event
  • focus — event when an element gets focus
  • blur — event when an element loses focus
  • change — event when the form element's value changes
  • input — event of data entry in a form element
  • select — event when text is selected in a form element

9.2 The submit Event

The submit event happens when a form is submitted. Usually, this is when a user hits the "Submit" button in the form. Handling this event can let you validate data before sending it to the server, stop the form from being sent when there's input errors, and do other stuff.

Example of handling the submit event:

HTML
    
        <form id="my-form" action="/submit" method="post">
          <label for="username">Username:</label>
          <input type="text" id="username" name="username">
          <button type="submit">Submit</button>
        </form>
    
  
JavaScript
    
      const form = document.getElementById('my-form');

      form.addEventListener('submit', function(event) {
        const username = document.getElementById('username').value;
        if (username === '') {
          alert('Please enter a username.');
          event.preventDefault(); // prevent form submission
        } else {
          alert(`Username received: ${username}`);
          event.preventDefault();
        }
      });
    
  
JavaScript
    
      const form = document.getElementById('my-form');

      form.addEventListener('submit', function(event) {
        const username = document.getElementById('username').value;
        if (username === '') {
          alert('Please enter a username.');
          event.preventDefault(); // prevent form submission
        }
      });
    
  

9.3 The reset Event

The reset event occurs when a form is reset to its initial state. This usually happens when a user clicks the "Reset" button. Handling this event can be handy for doing extra actions when resetting a form, like clearing error messages.

Example of handling the reset event:

HTML
    
      <div style="min-height: 220px">
        <form id="my-form">
          <label for="name">Name:</label>
          <br>
          <input type="text" id="name" name="name">
          <br><br>
          <label for="email">Email:</label>
          <br>
          <input type="email" id="email" name="email">
          <br><br>
          <label for="password">Password:</label>
          <br>
          <input type="password" id="password" name="password">
          <div style="margin-top: 10px">
            <button id="btn" type="button">Reset</button>
          </div>
        </form>
        <p id="log"></p>
      </div>
    
  
HTML
    
      <form id="my-form">
        <label for="name">Name:</label>
        <br>
        <input type="text" id="name" name="name">
        <br><br>
        <label for="email">Email:</label>
        <br>
        <input type="email" id="email" name="email">
        <br><br>
        <label for="password">Password:</label>
        <br>
        <input type="password" id="password" name="password">
        <div style="margin-top: 10px">
          <button type="reset">Reset</button>
        </div>
      </form>
      <p id="log"></p>
    
  
JavaScript
    
      const form = document.getElementById('my-form');
      const btn = document.getElementById('btn');
      const n = document.getElementById('name');
      const e = document.getElementById('email');
      const p = document.getElementById('password');
      const log = document.getElementById('log');

      document.addEventListener('DOMContentLoaded', () => {
        n.value = "John";
        e.value = "john@mail.com";
        p.value = "qwerty";
      });

      btn.addEventListener('click', () => {
        n.value = "";
        e.value = "";
        p.value = "";
        log.textContent = 'Form has been reset!';
      });
    
  
JavaScript
    
      const form = document.getElementById('my-form');
      const log = document.getElementById('log');

      form.addEventListener('reset', function () {
        log.textContent = 'Form has been reset!';
      });
    
  

9.4 The focus and blur Events

The focus and blur events happen when a form element gets and loses focus, respectively. These are often used to improve user interaction with the form, like showing hints or error messages.

Example of handling the focus event:

HTML
    
      <div style="min-height: 55px">
        <form id="my-form">
          <label for="username">Username:</label>
          <input type="text" id="username" name="username">
          <div id="username-hint" style="display: none;">
            You'll see this hint when the field is focused. 
            It'll remain visible even after focus is shifted.
          </div>
        </form>
      </div>
    
  
HTML
    
      <form id="my-form">
        <label for="username">Username:</label>
        <input type="text" id="username" name="username">
        <div id="username-hint" style="display: none;">
          You'll see this hint when the field is focused. 
          It'll remain visible even after focus is shifted.
        </div>
      </form>
    
  
JavaScript
    
      const form = document.getElementById('my-form');
      const usernameInput = document.getElementById('username');
      const hint = document.getElementById('username-hint');

      form.addEventListener("submit", (event) => {
        event.preventDefault();
      });

      usernameInput.addEventListener('focus', function (event) {
        hint.style.display = 'block';
      });
    
  
JavaScript
    
      const usernameInput = document.getElementById('username');
      const hint = document.getElementById('username-hint');

      usernameInput.addEventListener('focus', function () {
        hint.style.display = 'block';
      });
    
  

Example of handling the blur event:

HTML
    
      <div style="min-height: 55px">
        <form id="my-form">
          <label for="username">Username:</label>
          <input type="text" id="username" name="username">
          <div id="username-error" style="display: none; color: red;">
            Error will show only if the field is empty after losing focus
          </div>
        </form>
      </div>
    
  
HTML
    
      <form id="my-form">
        <label for="username">Username:</label>
        <input type="text" id="username" name="username">
        <div id="username-error" style="display: none; color: red;">
          Error will show only if the field is empty after losing focus
        </div>
      </form>
    
  
JavaScript
    
      const form = document.getElementById('my-form');
      const usernameInput = document.getElementById('username');
      const error = document.getElementById('username-error');

      form.addEventListener("submit", (event) => {
        event.preventDefault();
      });

      usernameInput.addEventListener('blur', function (event) {
        error.style.display = usernameInput.value === '' ? 'block' : 'none';
      });
    
  
JavaScript
    
      const usernameInput = document.getElementById('username');
      const error = document.getElementById('username-error');

      usernameInput.addEventListener('blur', function () {
        error.style.display = usernameInput.value === '' ? 'block' : 'none';
      });
    
  

9.5 The input Event

The input event fires every time the value of a form element changes, regardless of whether the element loses focus. This event is often used for real-time user input validation, like validating input fields as users type.

Example of handling the input event:

HTML
    
      <html lang="en">
        <head>
          <style>
            input {
              outline: none;
            }

            .valid {
              border-color: green;
            }

            .invalid {
              border-color: red;
            }

            .wrapper-valid::after {
              content: "Email is valid";
              margin-left: 5px;
              color: green;
            }

            .wrapper-invalid::after {
              content: "Email is invalid";
              margin-left: 5px;
              color: red;
            }
          </style>
        </head>
        <body>
          <form id="my-form">
            <label for="email">Email:</label>
            <div id="wrapper">
              <input type="email" id="email" name="email">
            </div>
          </form>
        </body>
      </html>
    
  
JavaScript
    
      const form = document.getElementById('my-form');
      const inputWrapper = document.getElementById('wrapper');
      const emailInput = document.getElementById('email');

      form.addEventListener("submit", (event) => {
        event.preventDefault();
      });

      emailInput.addEventListener('input', function () {
        const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

        if (emailPattern.test(emailInput.value)) {
          inputWrapper.classList.add('wrapper-valid');
          inputWrapper.classList.remove('wrapper-invalid');
          emailInput.classList.add('valid');
          emailInput.classList.remove('invalid');
        } else {
          inputWrapper.classList.add('wrapper-invalid');
          inputWrapper.classList.remove('wrapper-valid');
          emailInput.classList.add('invalid');
          emailInput.classList.remove('valid');
        }
      });
    
  
JavaScript
    
      const emailInput = document.getElementById('email');
      const inputWrapper = document.getElementById('wrapper');

      emailInput.addEventListener('input', function () {
        const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

        if (emailPattern.test(emailInput.value)) {
          emailInput.classList.add('valid');
          emailInput.classList.remove('invalid');
        } else {
          emailInput.classList.add('invalid');
          emailInput.classList.remove('valid');
        }
      });
    
  

9.6 The select Event

The select event occurs when a user selects text in a form element, like an input field or textarea. This event can be useful for performing actions when text is selected, such as showing a copy button.

Example of handling the select event:

HTML
    
      <div style="min-height: 55px">
        <form id="my-form">
          <label for="text-input">Enter text:</label>
          <input type="text" id="text" name="text">
          <div id="select-message"></div>
        </form>
      </div>
    
  
HTML
    
      <form id="my-form">
        <label for="text-input">Enter text:</label>
        <input type="text" id="text" name="text">
        <div id="select-message"></div>
      </form>
    
  
JavaScript
    
      document.addEventListener('DOMContentLoaded', function () {
        const form = document.getElementById('my-form');
        const textInput = document.getElementById('text');
        const selectMessage = document.getElementById('select-message');

        form.addEventListener("submit", (event) => {
          event.preventDefault();
        });

        textInput.addEventListener('select', function () {
          selectMessage.textContent = 'You selected some text!';
        });
      });
    
  
JavaScript
    
      document.addEventListener('DOMContentLoaded', function () {
        const textInput = document.getElementById('text');
        const selectMessage = document.getElementById('select-message');

        textInput.addEventListener('select', function () {
          selectMessage.textContent = 'You selected some text!';
        });
      });
    
  

9.7 The change Event

The change event fires when the value of a form element changes, and the user leaves the element (loses focus). This event is often used to check changes in form fields like dropdowns or checkboxes.

Example of handling the change event:

HTML
    
      <form id="my-form">
        <label for="color-select">Choose a color:</label>
        <select id="color-select" name="color">
          <option value="red">Red</option>
          <option value="green">Green</option>
          <option value="blue">Blue</option>
        </select>
      </form>
    
  
JavaScript
    
      document.addEventListener('DOMContentLoaded', function () {
        const form = document.getElementById('my-form');
        const selectElement = document.getElementById('color-select');

        form.addEventListener("submit", (event) => {
          event.preventDefault();
        });

        selectElement.addEventListener('change', function () {
          alert('You selected the color: ' + selectElement.value);
        });
      });
    
  
JavaScript
    
      document.addEventListener('DOMContentLoaded', function () {
        const selectElement = document.getElementById('color-select');

        selectElement.addEventListener('change', function () {
          alert('You selected the color: ' + selectElement.value);
        });
      });
    
  
1
Task
Frontend SELF EN, level 9, lesson 3
Locked
Form Reset
Form Reset
1
Task
Frontend SELF EN, level 9, lesson 3
Locked
Hints
Hints
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION