Level: Intermediate | Player: 19_Event_Processing
Learning Objectives
- Know the difference between input/change/submit events.
- Uses HTML5 built-in verification (required, type, pattern).
- Collect form data at once with
FormData. - Input values are controlled and verified using JavaScript.
- Learn the pattern of sending
preventDefaultto fetch, etc. when submitting.
1. input vs change vs submit
input: Whenever the value changes (every key during text input)change: When the focus is lost and the value changes (text), or as soon as the selection changes (select/checkbox)submit: When the form is submitted (form element)
form.addEventListener("submit", (e) => {
e.preventDefault();
//data processing
});
2. HTML5 validation
<input type="email" required minlength="3" />
The browser automatically verifies it. form.checkValidity(), can also be inspected in JavaScript with the validity object of the element.
3. FormData
const data = new FormData(form);
data.get("email");
for (const [k, v] of data) console.log(k, v);
FormData is also used for transfers including files.
4.controlled input
A pattern that JavaScript always holds the input value and reflects it on the screen.
input.addEventListener("input", (e) => {
state.value = e.target.value.toUpperCase();
input.value = state.value;
});
5. Submission pattern
form.addEventListener("submit", async (e) => {
e.preventDefault();
if (!form.checkValidity()) {
form.reportValidity();
return;
}
const data = new FormData(form);
//Transfer to fetch, which you will learn in the next lesson.
});
Core example
| file | Contents covered |
|---|---|
| index.html | Example form |
| 01_input_submit.js | input/submit event |
| 02_validation.js | Utilizing HTML5 Verification |
| 03_formdata.js | Using FormData |
| 04_controlled.js | JavaScript value control |
⚠️ Common Mistakes
preventDefaultis forgotten insubmitand the page is refreshed.- Access with
e.valueinstead ofe.target.value. - Confusion that the value of the checkbox is
.checkedand the text is.value. - When using FormData, the
nameproperty is omitted from input. - Domain verification, such as password matching, is intended to be processed only with HTML5.
❓ Frequently Asked Questions (FAQ)
Q1. Difference between checkValidity and reportValidity? A. checkValidity only checks, reportValidity displays a message to the user in case of failure.
Q2. Is controlled input always good? A. There may be a rendering cost for each key, so use it only when necessary.
Q3. Can file input also be transmitted as FormData? A. Yes, and it is automatically encoded as multipart/form-data.