JavaScript · Beginner level

Beginner level · Module 4: The DOM and Events · Lesson 2 of 3

Events and Forms

Respond to clicks, input and form submissions with event listeners, and read and validate form values.

In this lesson you will

  • Attach event listeners and use the event object
  • Handle form submission with preventDefault and validation

Key concepts

addEventListenerevent objectsubmit and preventDefaultinput validation

The lesson

element.addEventListener("click", handler) runs handler when the element is clicked. The handler receives an event object describing what happened, such as event.target, the element that triggered it.

Forms reload the page when submitted. Listen for the form's submit event and call event.preventDefault() to handle the data with JavaScript instead. Read values from inputs with input.value — always a string, so convert numbers with Number().

Validate before using values: check that required fields are filled and numbers are valid, show a message next to the field and keep focus on the first problem. HTML attributes such as required and min add a first layer of validation.

Step by step

  1. Add a click listener that counts button presses.
  2. Handle a form's submit event with preventDefault.
  3. Read and convert the form's values.
  4. Show validation messages for empty or invalid fields.

Practice activity

Build a fee payment form that validates the student name and amount and shows a confirmation message without reloading the page.

Expected result: Valid submissions show a confirmation; invalid ones show field-specific messages and nothing is submitted.

Check your understanding

  1. What does event.preventDefault() do on a form submit?

    Show answer

    Stops the browser's default action of submitting and reloading the page.

  2. What type is input.value?

    Show answer

    Always a string.

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.