Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.
Forms are an extremely important part of HTML and the Web Platform. They allow users to interact with the page—for example, to:
- search the site
- trigger filters to trim result pages
- send information
and much much more.
By default, forms submit their content to a server-side endpoint, which by default is the page URL itself:
<form>
...
<input type="submit" />
</form>
We can override this behavior by setting the action attribute of the form element, using the HTML method defined by the method attribute, which defaults to GET:
<form action="/contact" method="POST">
...
<input type="submit" />
</form>
Upon clicking the submit input element, the browser makes a POST request to the /contact URL on the same origin (protocol, domain and port).
Using JavaScript we can intercept this event, submit the form asynchronously (with XHR and Fetch), and we can also react to events happening on individual form elements.
Intercepting a form submit event
I just described the default behavior of forms, without JavaScript.
To work with forms using JavaScript, intercept the submit event on the form element:
const form = document.querySelector('form')
form.addEventListener('submit', (event) => {
// submit event detected
})
Inside the submit event handler, call event.preventDefault() to prevent the default behavior and stop the form from reloading the page:
const form = document.querySelector('form')
form.addEventListener('submit', (event) => {
// submit event detected
event.preventDefault()
})
At this point clicking the submit button will not do anything, except give us control.
Working with input element events
We have a number of events we can listen for in form elements:
inputfired on form elements when the element value is changedchangefired on form elements when the element value is changed. In the case of textinputelements andtextarea, it’s fired only once when the element loses focus (not for every single character typed)cutfired when the user cuts text from the form elementcopyfired when the user copies text from the form elementpastefired when the user pastes text into the form elementfocusfired when the form element gains focusblurfired when the form element loses focus
Here’s a sample form demo on Codepen: https://codepen.io/flaviocopes/pen/zQrqNy/
Lessons in this unit:
| 0: | Introduction |
| 1: | Handling events |
| 2: | The `DOMContentLoaded` event |
| 3: | The `event` object |
| 4: | Mouse events |
| 5: | Keyboard events |
| 6: | `preventDefault()` |
| 7: | Stopping event propagation |
| 8: | Bubbling and capturing |
| 9: | Form submit event |
| 10: | Input fields events |
| 11: | Creating custom events |
| 12: | Keyboard Events |
| 13: | Mouse Events |
| 14: | Touch Events |
| 15: | ▶︎ Form Events |