New! Explore our Programming Academy and AI Tutor - learn to code from scratch, free to start. Explore Now
Programming› JavaScript› Events and Forms

Events and Forms

💻 JavaScript

Respond to clicks, input and submits, and validate a form before sending it.

Lesson 6 of 9 Tutorial
0 of 9 completed

JavaScript becomes useful when it reacts to the user. Events tell your code when something happened.

By the end of this lesson you can:
  • 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.

Warning Client-side validation improves the experience but is not security. Always validate again on the server.

Practice

  1. Show a greeting when a button is clicked.
  2. Count the characters typed into a textarea.
  3. 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

Exercise 1. Validate a name field Medium
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.
JavaScript exercise-1.js
Expected Output
Short names are rejected with a visible error message.

Lesson Nav

Lesson sections