Start learning free

LESSON 39 OF 161 · FRONTEND: JAVASCRIPT IN THE BROWSER

Handle a Form in JavaScript

Practice

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.


STEP 1 OF 7
    Ctrl + Enter to check

    Dom Form Submit in JavaScript

    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free