Forms & User Input
Master the intricacies of user input. Learn the critical difference between input and change events, and how to safely extract data on submit.
The Gateway to Data
Forms are the primary way users send data to your application.
JavaScript provides specialized events specifically designed for reading text boxes, checkboxes, and form submissions.
Input vs Change
When a user types into a text field, you have two primary ways to listen to them:
1. The input event: Fires immediately on **every single keystroke**. Use this for live search filtering or real-time character counters.
2. The change event: Fires only when the user **commits** the change, usually by clicking outside the input box (losing focus) or pressing Enter. Use this for heavy validations that shouldn't run on every keystroke.
Handling the Submit
When a user clicks a Submit button, the submit event fires on the <form> element itself, *not* the button.
**Step 1:** You must call e.preventDefault() immediately to stop the browser from triggering a hard page refresh.
**Step 2:** Extract the data. You can read individual inputs using input.value, but modern JavaScript provides the FormData API. const data = new FormData(formElement) automatically bundles every named input in your form into a neat object.
The Form Inspector
Type into the input fields and click submit. Watch the terminal to see exactly when the input, change, and submit events fire, and how FormData extracts the values.
The Form Inspector
// Easily extract all named inputsconst data = new FormData(formEl);
Sign Up<form>
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- The
inputevent fires on every keystroke;changefires when the input loses focus. - The
submitevent fires on the<form>, not the button. - Always call
e.preventDefault()on a submit event to prevent a page refresh. - Use the modern
new FormData(formElement)API to easily extract all form data at once. - Inputs must have a
nameattribute to be captured byFormData.
Done with this concept?
Mark it complete to track your progress. No login needed.