LESSON 28

Forms with JavaScript

Learning objective: Read input values and validate forms with JavaScript.

Understand

JavaScript can read and check form input.

Listen for the form's submit event, call event.preventDefault() to stop a page reload, then read input values with .value. You can validate the data and show messages — all on the front end.

Analogy: This is like a receptionist checking a form is complete before accepting it.

See It in Action

Reading a value on submit:

form.addEventListener("submit", (e) => {
  e.preventDefault();
  const name = input.value;
  console.log(name);
});
How it works: preventDefault stops the default reload, then input.value reads what the user typed for validation.

Try It Yourself

  1. Listen for a form's submit event.
  2. Call preventDefault().
  3. Read and log an input's value.

Quick Quiz

Why call event.preventDefault() on submit?

Challenge

Read a name from a form and greet the user without reloading.

Success condition: Submitting the form shows a greeting and does not reload the page.