TalentJR

🟨 JavaScript tutorial for beginners · Class 8 · Lesson 12 of 18 · Free

Form Handling in JavaScript – Read, Check and Respond to User Input

⏱ About 35 minutes · ▶ run real JavaScript here — nothing to install · no sign-in

In this lesson you will

  • Read what the user typed with .value and turn text into numbers
  • Handle a form's submit event and stop the page from reloading
  • Validate inputs and show clear error or success messages on the page

Your school is opening sign-ups for the Science Quiz Club. Some students leave the name empty, some type Class 15, some add spaces everywhere. A good form catches these mistakes at once and tells the student, kindly, what to fix.

How do I get the value of an input box in JavaScript?

Every input box has a .value property: the text inside it right now. Read it when the user clicks — not when the page loads, or you get what was there at the start.

Important: .value is ALWAYS a string, even in a number box. Use Number() before doing maths, or "14" + 1 becomes "141".

Change the age and click the button. Watch the console.

🟨 JavaScript — you can edit this code
📄 HTML of the page (tap to see / edit)
🖥️ Your web page — try clicking it
Console output
string 13 → 14

How do I handle form submit in JavaScript without the page reloading?

Wrap inputs in a <form>. Then pressing Enter OR clicking the submit button fires one "submit" event. One listener handles both.

By default, a browser sends the form away and reloads the page — your JavaScript and the typed data are lost. event.preventDefault() says "stop, I will handle it myself".

The last line sends a test "submit" event from code, as if Join was pressed — so the console shows a result straight away. Then try it yourself: type a new name and press Enter or click Join.

🟨 JavaScript — you can edit this code
📄 HTML of the page (tap to see / edit)
🖥️ Your web page — try clicking it
Console output
Submitted: { name: "Ravi", cls: "8" }

💡 form.elements.student finds the field with name="student". { name, cls } is short for { name: name, cls: cls }.

How do I validate form input in JavaScript?

Validation means checking the input BEFORE using it. Write the checks in one function that takes the values and gives back an error message — or "" if all is fine.

Check the most basic problem first (is it empty?), then the details. Return as soon as you find a problem.

This function has no page at all, so you can test it with many values in the console. Watch each check in the trace.

🎬 How JavaScript thinks — step 1 of 20JavaScript is about to run line 9
1function checkSignup(name, cls) {
2 const clean = name.trim();
3 const c = Number(cls);
4 if (clean === "") return "Please type your name.";
5 if (clean.length < 2) return "Name is too short.";
6 if (!(c >= 6 && c <= 10)) return "Class must be 6 to 10.";
7 return "";
8}
▶console.log(checkSignup(" ", "8"));
10console.log(checkSignup("Meera", "15"));
11console.log(checkSignup("Meera", "8") === "" ? "All good!" : "Error");
📦 Variables (memory boxes)

No variables yet.

🖥️ Output
▌
✏️ Change this code and run it yourself
🟨 JavaScript — you can edit this code
Console output
Please type your name.
Class must be 6 to 10.
All good!

💡 ! means NOT. !(c >= 6 && c <= 10) is true when c is outside 6–10. It also catches Number("abc"), which is NaN (not a number).

How do I show an error message on the page instead of alert()?

alert() pops up a box the user must close, and it blocks the page. A message right next to the form is friendlier.

Use the same check function, then show the message in a <p> and add a CSS class to colour it. classList.toggle("bad", true/false) adds or removes the class.

Try: empty name, class 12, then a correct entry.

🟨 JavaScript — you can edit this code
📄 HTML of the page (tap to see / edit)
🖥️ Your web page — try clicking it
Console output
Waiting for you to press Sign up…

💡 After the first line, nothing prints until you press Sign up — the code waits for the submit event.

How do I read a select, a checkbox and radio buttons in JavaScript?

A <select> works like a text box: .value is the chosen option. A checkbox uses .checked, which is true or false.

Radio buttons with the same name form a group. form.elements.size.value gives the value of the chosen one.

Here is a canteen order. Change anything — the "input" event fires on every change, so the total updates live.

🟨 JavaScript — you can edit this code
📄 HTML of the page (tap to see / edit)
🖥️ Your web page — try clicking it
Console output
{ dish: "Dosa", qty: 2, chutney: true, size: "regular", total: 85 }

🤔 Predict the output

Think like JavaScript: read the code and choose what it prints. You get the reason straight away.

Question 1. An input's .value gave "14". What does this print?

const ageText = "14";
console.log(ageText + 1);

Question 2. The user typed only spaces. What does this print?

const name = "   ";
if (name.trim() === "") {
  console.log("Empty");
} else {
  console.log("Hello " + name);
}

Question 3. What does this print?

console.log(Number("8"), Number("eight"), Number(""));

🧩 Your challenge

Build a Quiz Club sign-up form. On submit: stop the reload, then check that the name has at least 2 letters (after trim) and the class is from 6 to 10. Show the error in red, or "Welcome, <name>!" in green, and console.log the message. Test it from code by sending a submit event twice (the starter shows how): first with the boxes as given (name " A ", class 12), then after setting name to "Asha" and class to 8. Expected output: Name needs at least 2 letters. Welcome, Asha!

Expected output in the console:
Name needs at least 2 letters.
Welcome, Asha!
🟨 JavaScript — you can edit this code
📄 HTML of the page (tap to see / edit)
🖥️ Your web page — try clicking it

⚠️ Common mistakes (and how to fix them)

❌ Wrong

const name = document.querySelector("#Name").value;
console.log("Hello", name);

TypeError: Cannot read properties of null (reading 'value')

✅ Right

const name = document.querySelector("#name").value;
console.log("Hello", name);

ids are case-sensitive: #Name does not match id="name", so querySelector gives null — and null has no .value.

❌ Wrong

const box = document.querySelector("#name");
const name = box.value;
document.querySelector("#go").addEventListener("click", () => {
  console.log("Hello, " + name);
});
console.log("Typed at start:", JSON.stringify(name));

No error — but it always says "Hello, " with no name, because .value was read once when the page loaded, while the box was still empty.

✅ Right

const box = document.querySelector("#name");
document.querySelector("#go").addEventListener("click", () => {
  const name = box.value;
  console.log("Hello, " + name);
});
console.log("Typed at start:", JSON.stringify(box.value));

Read .value inside the click handler, so you get what the user typed at the moment of clicking.

❌ Wrong

const form = document.querySelector("#f");
form.addEventListener("submit", () => {
  console.log("Saved:", form.elements.city.value);
});

No error — but on a real website the browser submits the form and reloads the page, so your message flashes and the typed data disappears.

✅ Right

const form = document.querySelector("#f");
form.addEventListener("submit", (e) => {
  e.preventDefault();
  console.log("Saved:", form.elements.city.value);
});

Always call e.preventDefault() first in a submit handler when JavaScript handles the form.

📌 Remember

  • input.value gives what is typed now — always a string; use Number() for maths.
  • Listen for "submit" on the form; it covers the button and the Enter key.
  • Call event.preventDefault() so the page does not reload.
  • Validate in one function: empty first, then details; return an error message or "".
  • Show messages on the page (textContent + a CSS class), not with alert().
  • select → .value, checkbox → .checked, radio group → form.elements.name.value.

Finished the quiz and the challenge?

Questions students ask

What does event.preventDefault() do in a form?

It stops the browser's normal action. For a form, that action is sending the data and reloading the page. Stopping it lets your JavaScript handle the data instead.

Why does my input value add like text in JavaScript?

Because .value is always a string, even for type="number". "5" + 1 joins into "51". Convert first with Number(box.value), or use box.valueAsNumber for number inputs.

How do I check an email address in JavaScript?

The easiest way is <input type="email" required>: the browser checks it for you on submit. For a simple check in code, test that it has an @ and a dot after it. Advanced programs use a pattern called a regular expression.

Is checking the form in JavaScript enough to keep data safe?

No. JavaScript checks help the user fix mistakes quickly. But anyone can switch them off, so a real website must check the data again on its server too.