Forms are an extremely important part of HTML and the Web Platform. They allow users can interact with the page and
- search something on 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.
In order to start working with forms with JavaScript you need to intercept the submit
event on the form element:
const form = document.querySelector('form')
form.addEventListener('submit', event => {
// submit event detected
})
Now inside the submit event handler function we call the event.preventDefault()
method to prevent the default behavior and avoid a form submit to reload the page:
const form = document.querySelector('form')
form.addEventListener('submit', event => {
// submit event detected
event.preventDefault()
})
At this point clicking the submit event button in the form will not do anything, except giving us the control.
Working with input element events
We have a number of events we can listen for in form elements
input
fired on form elements when the element value is changedchange
fired on form elements when the element value is changed. In the case of textinput
elements andtextarea
, it’s fired only once when the element loses focus (not for every single character typed)cut
fired when the user cuts text from the form elementcopy
fired when the user copies text from the form elementpaste
fired when the user pastes text into the form elementfocus
fired when the form element gains focusblur
fired when the form element loses focus
Here’s a sample form demo on Codepen:
See the Pen Form events demo by Flavio Copes (@flaviocopes) on CodePen.
Download my free JavaScript Beginner's Handbook
More browser tutorials:
- Some useful tricks available in HTML5
- How I made a CMS-based website work offline
- The Complete Guide to Progressive Web Apps
- The Fetch API
- The Push API Guide
- The Channel Messaging API
- Service Workers Tutorial
- The Cache API Guide
- The Notification API Guide
- Dive into IndexedDB
- The Selectors API: querySelector and querySelectorAll
- Efficiently load JavaScript with defer and async
- The Document Object Model (DOM)
- The Web Storage API: local storage and session storage
- Learn how HTTP Cookies work
- The History API
- The WebP Image Format
- XMLHttpRequest (XHR)
- An in-depth SVG tutorial
- What are Data URLs
- Roadmap to learn the Web Platform
- CORS, Cross-Origin Resource Sharing
- Web Workers
- The requestAnimationFrame() guide
- What is the Doctype
- Working with the DevTools Console and the Console API
- The Speech Synthesis API
- How to wait for the DOM ready event in plain JavaScript
- How to add a class to a DOM element
- How to loop over DOM elements from querySelectorAll
- How to remove a class from a DOM element
- How to check if a DOM element has a class
- How to change a DOM node value
- How to add a click event to a list of DOM elements returned from querySelectorAll
- WebRTC, the Real Time Web API
- How to get the scroll position of an element in JavaScript
- How to replace a DOM element
- How to only accept images in an input file field
- Why use a preview version of a browser?
- The Blob Object
- The File Object
- The FileReader Object
- The FileList Object
- ArrayBuffer
- ArrayBufferView
- The URL Object
- Typed Arrays
- The DataView Object
- The BroadcastChannel API
- The Streams API
- The FormData Object
- The Navigator Object
- How to use the Geolocation API
- How to use getUserMedia()
- How to use the Drag and Drop API
- How to work with scrolling on Web Pages
- Handling forms in JavaScript
- Keyboard events
- Mouse events
- Touch events
- How to remove all children from a DOM element
- How to create an HTML attribute using vanilla Javascript
- How to check if a checkbox is checked using JavaScript?
- How to copy to the clipboard using JavaScript
- How to disable a button using JavaScript
- How to make a page editable in the browser
- How to get query string values in JavaScript with URLSearchParams
- How to remove all CSS from a page at once
- How to use insertAdjacentHTML
- Safari, warn before quitting
- How to add an image to the DOM using JavaScript
- How to reset a form
- How to use Google Fonts