Chapter 19 — Forms
π― Goal (1 line)
Learn how to collect, validate, and process user input—the foundation of login pages, registration forms, search bars, and checkout forms.
Prerequisite: This chapter uses concepts from Chapters 17 (DOM) and 18 (Events). If you haven't studied those, don't worry—I briefly explain any new DOM methods when they first appear.
Quick Refresher (3 minutes)
Suppose you have this HTML:
<input id="name" type="text">
<button>Save</button>
JavaScript can read the input:
const input = document.querySelector("#name");
console.log(input.value);
New syntax
element.value
Returns whatever the user typed.
Example:
If the user types:
Alice
then
console.log(input.value);
prints
Alice
MCQ 1 (Easy)
Which property gets the text inside an input?
A.
input.text
B.
input.value
C.
input.innerHTML
D.
input.content
✅ Answer
B
Explanation:
Input elements store their content in the value property.
MCQ 2
What prints if the user typed John?
const input = document.querySelector("#name");
console.log(input.value);
A.
#name
B.
John
C.
value
D.
Error
✅ Answer
B
MCQ 3
Which event usually handles form submission?
A.
click
B.
change
C.
submit
D.
hover
✅ Answer
C
Explanation:
Forms usually listen for the submit event.
MCQ 4
What does this do?
event.preventDefault();
A.
Deletes the form
B.
Stops the browser's default behavior
C.
Refreshes the page
D.
Clears the input
✅ Answer
B
Explanation:
Without it, submitting a form reloads the page.
MCQ 5
Find the bug.
form.addEventListener("submit", () => {
console.log("Submitted");
});
A. No bug
B. Missing event.preventDefault()
C. Missing const
D. Wrong event name
✅ Answer
B
Explanation:
The page reloads unless you stop the default submit behavior.
Correct:
form.addEventListener("submit", (event) => {
event.preventDefault();
console.log("Submitted");
});
MCQ 6
Which is correct?
<input id="email">
A.
email.value
B.
document.querySelector("#email").value
C.
document.email
D.
email.text
✅ Answer
B
MCQ 7
Predict the output.
User types:
hello
Code:
const input = document.querySelector("#search");
console.log(input.value.length);
A.
4
B.
5
C.
6
D.
Error
✅ Answer
B
Explanation:
"hello" has 5 characters.
MCQ 8
How do you check if an input is empty?
A.
input.value === ""
B.
input.empty
C.
input.text === ""
D.
input.length === 0
✅ Answer
A
MCQ 9
Predict the output.
User types only spaces:
" "
Code:
console.log(input.value === "");
A.
true
B.
false
C.
undefined
D.
Error
✅ Answer
B
Explanation:
Spaces are still characters.
MCQ 10
Which is better?
A.
input.value === ""
B.
input.value.trim() === ""
✅ Answer
B
Explanation:
trim() removes spaces from both ends.
So
" "
becomes
""
MCQ 11
Predict the output.
User enters
Alice
Code:
console.log(input.value.trim());
A.
Alice
B.
Alice
C.
undefined
D.
Error
✅ Answer
B
MCQ 12
Find the bug.
if (input.value = "") {
console.log("Empty");
}
A.
No bug
B.
Should use ==
C.
Should use ===
D.
Need trim()
✅ Answer
C
Explanation:
= assigns.
=== compares.
This is one of the most common beginner mistakes.
MCQ 13
Which validation is best?
A.
if (password.length >= 8)
B.
if (password.value.length >= 8)
C.
if (password >= 8)
D.
if (password.text >= 8)
✅ Answer
B
Explanation:
The password is inside password.value.
MCQ 14
Predict the output.
User enters
12345678
Code:
if (password.value.length >= 8) {
console.log("Strong");
}
A.
Nothing
B.
Strong
C.
Weak
D.
Error
✅ Answer
B
MCQ 15
Find the better code.
A.
if (email.value === "") {
B.
if (email.value.trim() === "") {
✅ Answer
B
Users often type accidental spaces.
MCQ 16
Predict the output.
User types:
abc@gmail.com
Code:
console.log(email.value.includes("@"));
A.
true
B.
false
C.
undefined
D.
Error
✅ Answer
A
Explanation:
includes() checks whether a string contains another string.
MCQ 17
Which validation is stronger?
A.
email.value.includes("@")
B.
email.value.trim() !== "" &&
email.value.includes("@")
✅ Answer
B
Explanation:
First ensure it's not empty, then check for @.
MCQ 18
Predict the output.
const age = Number(input.value);
console.log(age + 5);
User types:
20
A.
205
B.
25
C.
Error
D.
undefined
✅ Answer
B
Explanation:
Without Number(), "20" + 5 would become "205".
MCQ 19
Find the bug.
const age = input.value;
console.log(age + 5);
User enters
20
A.
No bug
B.
Need Number()
C.
Need trim()
D.
Need parse()
✅ Answer
B
Explanation:
input.value is always a string.
MCQ 20 (Hard)
Predict the output.
User types
25
Code:
const age = Number(input.value);
if (age >= 18) {
console.log("Adult");
} else {
console.log("Minor");
}
A.
Minor
B.
Adult
C.
Error
D.
Nothing
✅ Answer
B
Common Beginner Mistakes
❌ Forgetting preventDefault()
❌ Comparing with = instead of ===
❌ Forgetting that input.value is always a string
❌ Not using trim() for empty input checks
❌ Validating the element instead of its .value
Mini Coding Challenge
Question
HTML
<input id="username">
<button id="check">Check</button>
JavaScript
const input = document.querySelector("#username");
const button = document.querySelector("#check");
button.addEventListener("click", () => {
if (input.value.trim() === "") {
console.log("Username required");
} else {
console.log("Welcome " + input.value.trim());
}
});
Predict the output.
Case 1
User enters
Alice
What prints?
✅ Answer
Welcome Alice
Case 2
User enters only spaces.
" "
What prints?
✅ Answer
Username required
Explanation:
trim() removes all leading and trailing spaces, leaving an empty string.
Mini Project — Login Form Validation
Problem
HTML
<form id="loginForm">
<input id="email" type="email">
<input id="password" type="password">
<button>Login</button>
</form>
Requirements:
Stop page refresh.
Read both inputs.
Remove extra spaces.
Email cannot be empty.
Password must have at least 8 characters.
Print:
"Login Successful"if valid.Otherwise print the appropriate error message.
✅ One Possible Solution
const form = document.querySelector("#loginForm");
const email = document.querySelector("#email");
const password = document.querySelector("#password");
form.addEventListener("submit", (event) => {
event.preventDefault();
const userEmail = email.value.trim();
const userPassword = password.value.trim();
if (userEmail === "") {
console.log("Email is required");
return;
}
if (userPassword.length < 8) {
console.log("Password must be at least 8 characters");
return;
}
console.log("Login Successful");
});
Example Outputs
Input
Email: alice@example.com
Password: password123
Output:
Login Successful
Input
Email:
Password: password123
Output:
Email is required
Input
Email: alice@example.com
Password: 12345
Output:
Password must be at least 8 characters
π― Chapter 19 Takeaways (The 20% That Gives You 80%)
These are the patterns you'll use in almost every web application:
Read user input with
input.value.Use
trim()before validating text input.Prevent form refresh using
event.preventDefault().Remember that
input.valueis always a string.Convert numeric input with
Number(input.value)when you need math.Validate early and return immediately when input is invalid (early return pattern).
Master these six ideas, and you'll be able to build login forms, signup pages, search bars, contact forms, and many other interactive features.
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.