Browser / JavaScript

JavaScript Events, Forms & Validation

Respond to users through events and create form experiences that validate, explain, and recover.

What you’ll learn

  • Use event listeners
  • Read form data
  • Provide accessible validation feedback

Before you start

You’ll need a modern browser, a basic HTML page, and a way to inspect the browser console. Practice with sample data. The interactive guide has its own activities and browser-saved progress.

Understand the idea

Events describe what happened and where. Register listeners in JavaScript instead of mixing behavior into HTML attributes.

Prevent submission only when JavaScript is handling it, read FormData, normalize values, and validate on clear rules.

Validation should explain what is wrong and how to fix it. Preserve user input and move focus thoughtfully when needed.

Follow the example

form.addEventListener('submit', event => {
  event.preventDefault();
  const data = new FormData(form);
  const title = String(data.get('title') || '').trim();
  if (!title) {
    status.textContent = 'Enter a task title.';
    return;
  }
  status.textContent = `Ready to add: ${title}`;
});

Listen for submit on the form so that keyboard submission works as well as a button click. Read and validate values before changing application state. Use an error message that explains what the user can fix.

Try it yourself

Build a task form with required title and optional notes. Test empty, whitespace-only, valid, keyboard, and repeated submissions.

Before you run the code, write down the result you expect. Change one input, test a boundary case, and explain why the output changes.

Practice this lesson in the full guide ↗

Build a small task list

Download the complete HTML practice project, open it in your browser, and change one behavior at a time. It combines form validation, safe DOM rendering, and browser storage.

Download the task list starter ↓

Common mistakes & troubleshooting

  • A button inside a form submits by default. Set type="button" for unrelated actions.
  • Call preventDefault only when your JavaScript handles the complete submission path.
  • Client-side validation improves feedback; a real server must validate submitted data independently.

Keep learning

Use your explanation to make a small feature of your own. Review the behavior before connecting it to real user data or a production application.