Form events

There are a list of events that are triggered by actions from inside a HTML form. Some commonly used events are listed below:

  • input - Triggered when an element gets an input.

  • change - Fired the moment when the value of the element is changed.

  • focus - fires the moment that the element gets focus

  • submit - fires when a form is submitted.

More events can be referenced from the MDN docs here: https://developer.mozilla.org/en-US/docs/Web/API/Element#events

Syntax recap

Event handlers can be set on HTML elements in two ways depending on your use case.

Declaring event handlers in HTML

The handlers can be set in as HTML element attributes by simply prefixing on to the event name. e.g.: submit -> onsubmit, focus -> onfocus

<html>
  <body>
    <script>
      function handler(){
        console.log('I am focussed')
      }
    </script>
    <form>
      <label>Text field</label>
      <input type="text" onfocus="handler()"> 
    </form>
  </body>
</html>

Declaring event handlers using JavaScript

The below example shows how you'd do the same in JavaScript, this is suitable for scenarios where the HTML content is dynamically created.

<html>

<body>
  <form>
    <label>Text field</label>
    <input type="text" id="text-field">
  </form>
  <script>
    function handler() {
      console.log('I am focussed')
    }

    document.getElementById('text-field').onfocus(handler)
  </script>
</body>

</html>

The above example shows one way of using JavaScript to set event handlers, can you find out the other method to do this in JavaScript?

References

Last updated