Events and Forms
💻 JavaScriptRespond to clicks, input and submits, and validate a form before sending it.
JavaScript becomes useful when it reacts to the user. Events tell your code when something happened.
- Attach event listeners.
- Read form values.
- Prevent invalid submissions.
Listening for Events
Use addEventListener instead of inline HTML attributes. It keeps behaviour in JavaScript and allows several listeners on one element.
const button = document.querySelector("#save");
button.addEventListener("click", () => {
console.log("Saved!");
});Reading a Form
Listen for the form's submit event, stop the default page reload, then read the fields.
const form = document.querySelector("#signup");
form.addEventListener("submit", (event) => {
event.preventDefault();
const email = form.elements.email.value.trim();
const password = form.elements.password.value;
if (!email.includes("@")) {
alert("Enter a valid email address.");
return;
}
if (password.length < 8) {
alert("Password must be at least 8 characters.");
return;
}
console.log("Submitting", { email });
});Input Events
The input event fires on every change. Use it for live character counts or search filtering. Debounce expensive work so it does not run on every keystroke.
Practice
- Show a greeting when a button is clicked.
- Count the characters typed into a textarea.
- Block a form submission when a required field is empty.
Hands-on exercise
Write JavaScript that listens for a form submit.
1. Read the value of an input named fullname.
2. If it is empty or shorter than 3 characters, prevent submission and show an error message.
3. Otherwise allow the submission.
Recap
Event listeners make pages interactive. Read form values carefully, prevent invalid submissions and always validate again on the server.
Example
const button = document.querySelector("#save");
button.addEventListener("click", () => {
console.log("Saved!");
});
Exercises
1. Read the value of an input named fullname.
2. If it is empty or shorter than 3 characters, prevent submission and show an error message.
3. Otherwise allow the submission.
Expected Output
Short names are rejected with a visible error message.