Forms
Forms collect information from people: sign-ups, searches, checkouts, comments.
HTML
<form>
<label for="name">Your name</label><br>
<input id="name" name="name" type="text" placeholder="Asha"><br><br>
<label for="email">Email</label><br>
<input id="email" name="email" type="email" placeholder="asha@example.com"><br><br>
<button type="submit">Sign up</button>
</form>The pieces
| Element | Purpose |
|---|---|
<form> | wraps the fields; action and method say where and how to send the data |
<label> | the visible name of a field |
<input> | a one-line field (text, email, password, checkbox...) |
<textarea> | multi-line text |
<select> + <option> | a drop-down list |
<button> | submits the form (or does something else with type="button") |
Always connect labels
A label's for must match its input's id. Then clicking the label focuses the field, and screen readers announce the label:
HTML
<input type="checkbox" id="terms">
<label for="terms">I accept the terms (click this text)</label>More field types
HTML
<form>
<label for="msg">Message</label><br>
<textarea id="msg" name="message" rows="3" cols="30"></textarea><br><br>
<label for="course">Course</label>
<select id="course" name="course">
<option>Python</option>
<option selected>JavaScript</option>
<option>SQL</option>
</select><br><br>
<p>Level:</p>
<input type="radio" id="beg" name="level" value="beginner" checked><label for="beg">Beginner</label>
<input type="radio" id="int" name="level" value="intermediate"><label for="int">Intermediate</label>
</form>Radio buttons with the same name form a group: only one can be selected.
The name attribute
When a form is sent, each field's value is sent with its name. A field without a name isn't submitted at all.
Where the data goes
HTML
<form action="/subscribe" method="post">actionis the URL that receives the data.method="get"puts the data in the URL (good for searches);method="post"sends it in the request body (for anything private or that changes data).
In a static page with no server, JavaScript usually handles the submit event instead, as in the JavaScript events lesson.
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.