Saltar para o conteúdo principal
← ⚡ JavaScript & the browser·Módulo C2 · Lição 6
TarefaBuild a form: <form id='f'><input id='email' name='email' type='email' required /><button type='submit'>Send</button></form>. Plus <p id='out'></p>. On submit: preventDefault, read email via FormData, write 'sent: <email>' into #out. Console.log 'submitted' too.

Envio de formulário + preventDefault: interrompe o recarregamento da página

100 XP8 min
Teoria

The default form-submit behaviour

When you click a submit button or press Enter in an input, the browser:

  1. Builds a form payload (every named input's value).
  2. Navigates the browser to the URL in action=, replacing the page.

In modern SPAs you almost always want to handle the submit in JavaScript instead — keep the page alive, send the data via fetch, update part of the UI.

The intercept

form.addEventListener("submit", (event) => {
  event.preventDefault();
  // your code: build payload, call fetch, update UI
});

preventDefault() cancels the navigation. The form stays put. You're now in charge.

Read all fields cleanly: FormData

const data = new FormData(form);
data.get("email");          // single value
[...data.entries()];        // array of [name, value] pairs
const obj = Object.fromEntries(data);

FormData understands files, multi-value selects, checkboxes — all the edge cases hand-coded readers miss. It's the standard browser way to read a form.

Don't break native validation by accident

event.preventDefault() cancels submission. If you call it BEFORE checking form.checkValidity(), you've also bypassed the browser's built-in required/pattern checks. Either let the browser validate first, or rebuild the same checks in your handler.

🔒

Regista-te para começar a programar

A teoria está aberta a todos. O editor, a pré-visualização e o check desbloqueiam-se com um teste gratuito de 7 dias — cartão obrigatório, cancelável a qualquer momento.

Registar — teste grátis →

As primeiras 10 lições de cada trilha são grátis. Sem cartão necessário.

← AnteriorPróxima lição →

Recebe uma dica de Python ou web por dia — por email

Curto, escrito à mão, sem spam. Cancela a subscrição num clique.