JavaScript - 21
JavaScript - 21: Form Handling
Forms let users enter information that JavaScript can read and use.
In this lesson, you will read a name and age from a form and display a personalized message below it.
Your challenge: Listen for the form submission, read both input values, and show the result on the page.
Listen for the form submission
Select the form with: document.getElementById("userForm")
Then listen for its submit event: form.addEventListener("submit", function(event) { ... });
Using the form's submit event means the form can work from the button or normal keyboard submission.
Prevent the normal form behavior
Inside the event listener, use: event.preventDefault();
This stops the browser from performing its normal form submission so JavaScript can update the page instead.
Read the input values
Use the .value property to get what the user entered:
const name = document.getElementById("name").value;
const age = document.getElementById("age").value;
Display the result
Use a template literal to combine the values:
`Hello ${name}! You are ${age} years old.`
Then place the message in the result paragraph with .textContent.
Try it: Enter different names and ages and submit the form several times.
Small experiment: Add .trim() to the name value to remove extra spaces from the beginning and end.
Good JavaScript habit: Use the form's submit event instead of only listening for a button click. It keeps form behavior more flexible and predictable.
👀 Show Solution
const form = document.getElementById("userForm");
const result = document.getElementById("result");
form.addEventListener("submit", function(event) {
event.preventDefault();
const name = document.getElementById("name").value.trim();
const age = document.getElementById("age").value;
result.textContent = `Hello ${name}! You are ${age} years old.`;
});The form event reads the entered values, prevents the normal submission, and updates the result paragraph without reloading the page.
