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>
formwraps everything.actionis the URL the data goes to, andmethod="post"means send data rather than just fetch a page.inputis a void element that renders a text box. Itsnameis the key the server receives the value under.labelnames the field for humans. Itsforattribute must equal the input'sid(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
buttonsubmits the form.
Input types
One element, many behaviors. The type attribute changes both the widget and the built-in checks:
| type | what you get |
|---|---|
text | plain one-line text box |
email | text box, and the browser blocks submits without a valid-looking email |
password | characters shown as dots |
number | numeric keyboard on phones, respects min and max |
checkbox | an on/off box |
radio | pick 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 @.