Loading video player…

Send the Form Without a Reload

Sam would rather press Enter than reach for the mouse, but on the last lesson’s page, Enter in the How many? box did nothing. In this video, you wrapped the shopping list’s fields in a form, watched the page reload, and moved the Add code to a listener that keeps the page in place. Here are the key points:

  • A <form> element groups fields that are sent together. Pressing Enter in one of its text boxes sends the form, when the form has a submit button, as yours does.
  • Sending a form is built into the browser. With this form’s default settings, the browser loads a page and puts the named field values after a question mark. A form that doesn’t say which page to load loads its own page again, so the boxes empty and your script starts over. The shopping list’s fields have no name attributes yet, so nothing follows the ?. A name isn’t the same as an id. A reload keeps that ?, so load the plain address before each try.
  • An ordinary button in this form defaults to submit. The Add button has no type, so clicking it sends the form. For a button that runs your own code, such as a Clear list button, use type="button".
  • Pressing Enter in this form’s boxes clicks its submit button for you. With event.preventDefault() in the Add button’s click listener, Enter still added the row, because the click listener ran and canceled the send.
  • A click listener that calls preventDefault() cancels the send before the browser checks the form, for example that a required box isn’t empty, so those checks never run. You’ll set up checks later in this course. That’s all you need about them for now.
  • The form fires a submit event when it’s really being sent, only after its checks pass. So listen for submit on the form, not click on its button.
  • Loading a page is what sending does by default. Before, preventDefault() stopped the click from sending the form, so submit never fired. A submit listener without preventDefault() runs, and then the browser reloads the page anyway. Make event.preventDefault() the submit listener’s first line, and the page stays put.

In kitchen/index.html, the two labels and the Add button now sit inside a form with the id add-form, and the rest of <main> stays as it was:

Language: HTML Filename: kitchen/index.html
<form id="add-form">
  <label>
    Item
    <input id="item-name">
  </label>
  <label>
    How many?
    <input id="item-count" type="number">
  </label>
  <button id="add-item">Add</button>
</form>

In kitchen/main.js, store the form in a constant named form beside the other lookups, and change the Add listener’s first line to listen for submit on the form, with event.preventDefault(); first. The checks and addItem() are the last lesson’s, unchanged. Here’s the whole file:

Language: JavaScript Filename: kitchen/main.js
const nameInput = document.querySelector("#item-name");
const countInput = document.querySelector("#item-count");
const addButton = document.querySelector("#add-item");
const nextLine = document.querySelector("#next");
const message = document.querySelector("#message");
const itemList = document.querySelector("#items");
const form = document.querySelector("#add-form");

function addItem(name, count) {
  const item = document.createElement("li");
  item.textContent = `${name} (${count})`;
  itemList.append(item);
}

form.addEventListener("submit", (event) => {
  event.preventDefault();
  const name = nameInput.value.trim();
  const countText = countInput.value.trim();
  const count = Number(countText);
  if (name === "") {
    message.textContent = "Type the item's name first.";
  } else if (countText === "" || Number.isNaN(count)) {
    message.textContent = "Type how many you need, like 3.";
  } else {
    message.textContent = "";
    addItem(name, count);
  }
});

function showNext() {
  const name = nameInput.value.trim();
  nextLine.textContent = `Next: ${name} (${countInput.value})`;
}

nameInput.addEventListener("input", showNext);
countInput.addEventListener("input", showNext);

Load the page at its plain address, type eggs and 3, and press Enter. The row eggs (3) appears, and the address stays the same. The boxes keep what you typed, so clicking Add puts a second eggs (3) row on the list. Emptying the form comes in the next lesson.

Now Enter and the Add button both add Sam’s item, and nothing reloads. Next, in Read a Whole Form With FormData, you’ll read a bigger form all at once.

00:00 From the last lesson, Sam’s shopping list has an Item box, a How many box and an Add button, whose click listener puts a new row on the list. Sam would rather press Enter than reach for the mouse.

00:13 Type eggs, then three, and press Enter. Nothing happens. In HTML, a form element groups fields that are sent together. Pressing Enter in one of its text boxes sends the form, when it has a submit button, as yours will.

00:29 So wrap the two labels and the Add button in a form with the id add-form, and keep the click listener.

00:37 Save, reload, type eggs and three, and press Enter. Your listener adds the row, but the page reloads from scratch straight away. Both boxes are empty, and the address now ends in a question mark.

00:52 A reload keeps that question mark, so start each try from the plain address. Then a new question mark tells you the form was sent. Click Add instead, and the same thing happens.

01:04 Sending a form is built into the browser. With this form’s default settings, the browser loads a page and puts the named field values after a question mark.

01:13 This form doesn’t say which page to load, so the browser loads this one again, and your script starts over. Nothing follows the question mark, because your fields have no name attributes yet.

01:23 A name isn’t the same as an id.

01:27 Why did clicking Add send it? An ordinary button in a form is a submit button, so it sends the form. Add has no type, so it’s one.

01:38 You’ve stopped a browser default before. To keep Priya’s House rules link from jumping down to her rules, its click listener took the event object and called its preventDefault method.

01:49 That cancels what the browser would do next. Do the same for Add. Give the click listener the event parameter, and make event.preventDefault() its first line.

02:00 Then click Add. The row appears, and the address stays put. Your turn: pause the video and predict what pressing Enter does now, with preventDefault in the click listener only.

02:17 The row appears, and the page stays put.

02:22 Pressing Enter in this form’s boxes clicks its submit button for you. So your click listener ran, and its preventDefault canceled the send.

02:32 That works, at a cost. Before sending a form, the browser checks it, for example that a required box isn’t empty. Your click listener cancels the send before those checks, so they never run.

02:44 You’ll set up checks later in this course, and that’s all you need about them for now. The form itself fires a submit event when it’s really being sent, only after its checks pass.

02:56 So store the form in a constant named form, and change the listener’s first line to listen for submit on the form.

03:05 Now that sending fires submit, the preventDefault line looks like it can go. Delete it, and the event parameter with it. Then press Enter. The page reloads again, with empty boxes and the question mark.

03:20 Before, preventDefault stopped the click from sending the form, so submit never fired. Now it’s sent, and sending loads a page by default. Your listener runs, and then the browser reloads anyway.

03:33 So put the event parameter and the preventDefault line back, and press Enter. The row appears, and the page stays. The boxes keep what you typed, so clicking Add puts a second row on the list.

03:45 Emptying the form comes in the next lesson.

03:49 As a rule, handle a form with a submit listener on the form, not a click listener on its button. Make event.preventDefault() its first line, so the page stays put.

04:00 And give a button that runs only your own code, such as a Clear list button, type=”button”.

04:07 Now Enter and the Add button both add Sam’s item, and nothing reloads. Next, in Read a Whole Form With FormData, you’ll read a bigger form all at once.

Become a Member to join the conversation.