CodeBlanks Logo Icon CodeBlanks

Summary - Forms

JavaScript course · Intermediate · Lesson 59/134

Build an app that collects and displays data from a registration form using the submit event and validation.

Summary - Working with forms

In this group you learned to work with forms. You used querySelector to reach a form, and form.elements with value to read its fields. You caught the submit event and stopped the page reload with preventDefault.

For validation you checked empty with trim and length with length. For checkboxes you used checked, and for radio groups you used querySelectorAll with a loop.

Validation flow

The validation flow is: first catch the submit event, then stop the reload with preventDefault. Then read the fields with form.elements and clean them with trim.

form.addEventListener('submit', (event) => {
  event.preventDefault();
  const name = form.elements['name'].value.trim();
});

On empty or too short values you warn the user; on valid values you continue the work.

Exercise Process the registration form

The form variable points to a registration form. Add a submit listener and stop the page reload. Trim the value of the 'name' field and log 'Name required' if empty; otherwise log 'Welcome'. Finally check the checkbox named 'agree': if selected, log 'Confirmed'.

Show example solution
form.addEventListener('submit', (event) => {
  event.preventDefault();
  const name = form.elements['name'].value.trim();
  if (name === '') {
    console.log('Name required');
  } else {
    console.log('Welcome');
  }
  const agree = form.elements['agree'];
  if (agree.checked) {
    console.log('Confirmed');
  }
});

Test yourself

  1. Which is a correct submit listener skeleton?

    // A
    form.addEventListener('click', (e) => { e.preventDefault(); });
    // B
    form.addEventListener('submit', () => { console.log('Send'); });
    // C
    form.addEventListener('submit', (e) => { console.log('OK'); });
    // D
    form.addEventListener('submit', (e) => { e.preventDefault(); console.log('Submitted'); });
    • A
    • B
    • C
    • D
    Show answer

    D — Correct! Option D catches the submit event, calls preventDefault to stop reload, and logs output.

  2. Match concepts to their meanings

    form.elements
    Form field collection
    event.preventDefault()
    Stops page reload
    input.checked
    Is checkbox selected
  3. Complete the submit listener skeleton

    form.addEventListener('submit', (event) => {
      event.____();
      const name = form.elements['name'].value.trim();
    });
    Show answer
    form.addEventListener('submit', (event) => {
      event.preventDefault();
      const name = form.elements['name'].value.trim();
    });

All lessons in Intermediate