Syncing account progress…

Back

Intermediate · 12 min

Read and validate forms

Handle form submission, read input values, and show a useful response.

Starting HTML

<form id="greeting"><label for="name">Name</label><input id="name" type="text"><button id="submit" type="submit">Greet</button></form>
<p id="message">Ready</p>

Handle the form event

Listen for submit on the form so both button and keyboard submission follow the same path. preventDefault() stops the normal navigation. Read an input through its value property.

const form = document.querySelector("#greeting");
form.addEventListener("submit", event => {
  event.preventDefault();
  document.querySelector("#message").textContent = document.querySelector("#name").value;
});
document.querySelector("#name").value = "Ada";
form.dispatchEvent(new Event("submit", { bubbles: true, cancelable: true }));
console.log(document.querySelector("#message").textContent);

Output

Ada

Validate before using input

Input values are strings. Trim unwanted outer whitespace and handle empty input before building the response. Display user input with textContent.

const value = "  Mina  ".trim();
console.log(value ? `Hello, ${value}!` : "Enter a name");

Output

Hello, Mina!

Put it into practice

  1. Predict each result before running the example.
  2. Complete the coding task, then explain why your solution works.

Try it yourself

Code runs on this device. When you are signed in, drafts sync to your account.

Greet the submitted name

Trim the name when the form is submitted. Show "Enter a name" for blank input; otherwise greet the entered name. The check submits a padded name.

Page preview

Run your code, then try the controls below. Check solution resets the page and tries the actions described in the task.

Practice