A form sends itself. When a visitor clicks a form's button, or presses Enter in one of its fields, the browser packs up the fields, sends them away and loads a new page. Your script goes away with the old page.
Just before sending, the form fires a submit event. A listener for it can call event.preventDefault(): the browser then skips its own sending, and your script decides what happens. Here is a search form that stays on its page:
const finder = document.querySelector("#finder");
const words = document.querySelector("#words");
finder.addEventListener("submit", (event) => {
event.preventDefault();
console.log("Searching for " + words.value);
});
A field's value is what the visitor typed in it. Writing to value changes what the field shows.
The check types an address into the newsletter form and clicks Subscribe. Your page must show:
> type "ana@example.com" into "Email"
field "Email": "ana@example.com" (email)
> click "Subscribe"
field "Email": "" (email)
button: Subscribe
text: Thanks, ana@example.com
Without preventDefault, the check prints the browser sends the form itself and loads a new page after the click.
Your task: find the newsletter form, its Email field and the empty #thanks paragraph. Listen for the form's submit: stop the browser's own sending, write "Thanks, " and the address into #thanks, and empty the field.
Assignment
Follow the Coding Tutorial to handle the newsletter form's submit event in app.js, below the search listener.
Hint
Read email.value before you empty the field. event.preventDefault() goes at the top of the listener.
Free plan: 30 tutor messages. PRO is unlimited.
