×

javascript · level 2 · unit 4 · lesson 1

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

Listen for on the , then stop the reload.

A form wraps fields and a button in <form> tags. When someone presses the button, or Enter in a field, the form fires a submit event. Listen on the form itself, not the button, and both ways are caught.

Left alone, a browser sends a form by loading a new page, which wipes out everything your code did. stops that, so your listener can handle the form itself.

Inside the listener, read each field's .value, then use it.

<form id="signup">
  <input id="email" placeholder="Your email">
  <button>Join the club</button>
</form>
<p id="thanks"></p>
const form = document.querySelector("#signup");
const email = document.querySelector("#email");
form.addEventListener("submit", (event) => {
  event.preventDefault();
  document.querySelector("#thanks").textContent = `Welcome, ${email.value}!`;
});

Press run it to bring the page to life.

console

nothing logged yet

Gwecode's preview never really sends a form, but real pages do, so always call preventDefault().