JavaScript Simplified · One concept, one day, one project · Day 19 of 32
Form Handling
Taking information from a user through a form, the right way. You build a registration form that collects details and shows them back.
By the end of today you can
- Read what a user typed with
.value - React to a form being sent with the
submitevent - Stop the page reloading with
preventDefault - Build a registration form
Forms are how users give you real information: their name, email, a message, a payment. Handling a form well is a core skill, and it has one surprise that trips up every beginner once. Today you learn it properly.
1. Reading a Field
An input’s .value is whatever the user typed in it. Select the input, read its value.
2. The submit Event and preventDefault
The surprise
When a form is submitted, the browser’s default behaviour is to reload the page. That wipes out your JavaScript before it can do anything. So the first thing every form handler does is call preventDefault to stop that reload.
The handler receives an event. Calling event.preventDefault() stops the reload, so your code runs: it reads the name and shows a greeting. Forget that one line and the form just flashes and clears.
Today’s Mini Project
📝 Registration Form
Collect a name, email and age from a form, and display the submitted details back on the page. This is the pattern behind every sign-up you have ever filled in.
Before showing the summary, add a confirmation line "Welcome, " + name + "!" above it. Expected: two lines appear after registering, a welcome and the details.
Add a "message" input to the form and include it in the summary.
Expected: the submitted message appears alongside the name and email.
Every account you have ever made began with a form just like this: read the fields, stop the reload, do something with the values. You can now take information from a user, the first half of every real app.
Checkpoint
How do you read what a user typed in an input?
With its .value, for example document.getElementById("name").value. It holds whatever the user typed.
Why call event.preventDefault in a submit handler?
Because a form submit reloads the page by default, which wipes out your JavaScript. preventDefault stops the reload so your code can run.
What does the submit event let you do?
Run your own code when the form is sent, so you can read the fields and respond on the page instead of reloading.
Tick Before You Move On
- ☐ I can read a field with .value
- ☐ I can react to a form with the submit event
- ☐ I can stop the reload with preventDefault
- ☐ I built the Registration Form
Quick Recap
.value holds what the user typed in an input. The submit event lets you run code when a form is sent. A form submit reloads the page by default; preventDefault stops that. Read the fields, prevent the reload, then do something with the values.
Next: Day 20. Taking input is not enough; you must check it is sensible. Tomorrow you validate a form and show helpful error messages.