Sending a Form

When a page asks for several things at once, its fields go into a form: the form element. A form has a button that sends it, a button with type="submit":

<form id="newsletter">
    <label for="email">Email</label>
    <input id="email">
    <button type="submit">Sign up</button>
</form>
<p id="thanks"></p>

The user sends the form by clicking the button, or by pressing Enter in one of its fields. Either way, the form gets the event submit, so that's where the handler goes: on the form, not on the button.

When a form is sent, the browser also does something by itself: it sends what was typed to a server and loads the page again. That's its default action, and on a page whose script takes care of the form, it gets in the way: the page starts over, everything typed is gone, and so is whatever your handler showed. Try it in this exercise's preview: type something into the fields and click the button. The page loads again, and the fields are empty. The method event.preventDefault() tells the browser not to do its default action:

const form = document.querySelector("#newsletter");
const emailInput = document.querySelector("#email");
const thanks = document.querySelector("#thanks");

form.addEventListener("submit", function (event) {
    event.preventDefault();
    thanks.textContent = `Thank you! We'll write to ${emailInput.value}.`;
});

Call it first, at the start of the handler: if something below it ends with an error, the page still won't reload.

Typical mistakes:

  • event.preventDefault; without parentheses doesn't call the method, so it does nothing, and the page reloads.
  • A button inside a form sends the form even without type="submit". When a form has another button, one that shouldn't send it, give that button type="button".

Instructions

When form is submitted, stop the browser from loading the page again with event.preventDefault(), and add a new item to the end of entryList: the name, a colon and the message, for example Tom: Hello from Prague!. Try sending the form with the button and with Enter.

After adding the entry, empty both fields, so that the next guest can write right away.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

Back

8/10

Next