DevNotes
@devnotes ·
HTML Part 4: Forms and buttons
Every sign-up, search box and comment box is a form. Here's how to build one that's easy to fill in, on a laptop or a phone.
A small form
A few things are going on here.
<label> is the text that says what goes in the box. Its for matches the input's id, and that links the two: clicking the label puts the cursor in the box, and screen readers read the label out when someone reaches the box. Every input needs a label.
name is what the data is sent as. If someone types Asha, the form sends name=Asha. An input without a name isn't sent at all, and that's a common reason for data going missing.
required stops the form from sending while that box is empty. The browser shows the warning message itself.
Input types
The type changes what a box accepts, and on phones it changes the keyboard too. (Labels are left out here to keep it short.)
email also checks that what's typed looks like an email address before the form sends.
Choices
For one choice out of a few, use radio buttons that share a name:
Both have name="meal", so picking one unpicks the other. value is what gets sent.
A checkbox is a yes or no on its own: <input type="checkbox" id="terms" name="terms">.
For a longer list of options, use a dropdown:
For longer text, like a message, use <textarea>:
A placeholder is not a label
placeholder="e.g. Asha" shows grey hint text inside the box, but it disappears the moment someone starts typing. Use it for an example, never in place of a label.
Buttons
Inside a form, a <button> sends the form unless you say otherwise. A button that does something else, like showing the password, needs type="button". Writing type="submit" on the real one makes your intent clear to anyone reading the code.
Where does the data go?
<form action="/join" method="post"> would send it to a server at /join. With no action, the form sends the data to the same page: it reloads, and you'll see something like ?name=Asha&email=... at the end of the address. In the JavaScript series you'll catch the data yourself, without the reload.
Try it
Build a sign-up form for a college fest: name, email, phone, year (a dropdown), and a checkbox for "I'd like to volunteer". Open it on a phone (CodePen makes this easy) and tap each box to watch the keyboard change.
Next: HTML Part 5: Structure a whole page
Join WIK to like and reply to DevNotes and see more like this.