Course outline · 0% complete

0/30 lessons0%

Course overview →

Forms and inputs

lesson 3-1 · ~10 min · 7/30

Quiz

Warm-up from lesson 2-1: in <a href="/apply">Apply</a>, what is href="/apply"?

Forms collect input

Everything you have built so far only shows content. A form collects it — and collecting input is where the web earns money and gets work done: every login, search box, checkout, and signup on the internet is a form. It is also where accessibility and validation bugs cluster, which is why interviewers love asking about the details below.

<form action="/signup" method="post">
  <label for="email">Email</label>
  <input id="email" name="email" type="email">

  <button type="submit">Sign up</button>
</form>
  • form wraps everything. action is the URL the data goes to, and method="post" means send data rather than just fetch a page.
  • input is a void element that renders a text box. Its name is the key the server receives the value under.
  • label names the field for humans. Its for attribute must equal the input's id (the unique element name from lesson 2-3). Then clicking the label focuses the input, and screen readers announce the field properly. Every input gets a label.
  • The button submits the form.

Input types

One element, many behaviors. The type attribute changes both the widget and the built-in checks:

typewhat you get
textplain one-line text box
emailtext box, and the browser blocks submits without a valid-looking email
passwordcharacters shown as dots
numbernumeric keyboard on phones, respects min and max
checkboxan on/off box
radiopick one of a group (give the group one shared name)

Two more form friends: <textarea> for multi-line text, and <select> with <option> children for dropdowns.

Add the required attribute to any field and the browser refuses to submit while it is empty. That is free validation before you write a single line of JavaScript. In lesson 9-3 you will write the JavaScript version for custom rules.

Quiz

A label's for attribute must match which attribute on the input?

Build the signup field. Inside the form, add: 1) a label with for="email" saying Email, 2) an input with id="email", name="email", type="email", and the required attribute, 3) a submit button saying Sign up. Then click your label in the preview: if the input gets focus, the pairing works.

Code exercise · javascript

The browser's type="email" check is a black box, so write your own simple version. looksLikeEmail(value) is true only if the string has exactly one @ with at least one character before it, and a dot somewhere after the @.