javascript · level 2 · unit 4 · lesson 1
- meet it
- guess first
- your turn
- fix it
- 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().
guess first
Saturn is typed and the form is sent. What shows?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<form id="pick">
<input id="planet" placeholder="Favourite planet">
<button>Send</button>
</form>
<p id="answer">No answer yet</p> const planet = document.querySelector("#planet");
document.querySelector("#pick").addEventListener("submit", (event) => {
event.preventDefault();
document.querySelector("#answer").textContent = `You chose ${planet.value.toUpperCase()}`;
});
your turn
Your turn. Wire up a newsletter form.
Fill in the event a form fires when it is sent, then the method that stops the reload. Press run, type a name and press the button.
the page your code works on
<form id="news">
<input id="reader" placeholder="Your first name">
<button>Sign me up</button>
</form>
<p id="note"></p>your javascript
Press run it to bring the page to life.
console
nothing logged yet
- sending the form thanks Mayanot checked yet
fix it
Nothing happens when the order is sent. Fix it!
the page your code works on
<form id="order">
<input id="pizza" placeholder="Which pizza?">
<button id="send">Order</button>
</form>
<p id="kitchen">The kitchen is waiting</p>your javascript
Press run it to bring the page to life.
console
nothing logged yet
- the kitchen gets the ordernot checked yet
- There is no error, but the listener never runs. Which element is it listening on?
- The
submitevent belongs to the form, not to the button inside it. - Change #send to #order on line 2, then press run.
nailed it
your forms are wired up. :D
- Listen for
submiton the form, not the button. - Call
event.preventDefault()first to stop the reload. - Read each field's
.valueinside the listener.
new words in your collection
- form
- submit
- preventDefault
This lesson isn’t saved. A free account remembers every lesson you finish.