Chapter 7 of 10
Forms are how websites collect information from users โ login details, search queries, contact messages, orders. Every form you've ever filled out online was built with HTML form elements.
<form action="/submit" method="POST">
<!-- Text input -->
<label for="name">Full Name</label>
<input type="text" id="name" name="name" placeholder="Nelson Njihia" required />
<!-- Email -->
<label for="email">Email Address</label>
<input type="email" id="email" name="email" required />
<!-- Password -->
<label for="password">Password</label>
<input type="password" id="password" name="password" minlength="8" required />
<!-- Dropdown select -->
<label for="course">Which course?</label>
<select id="course" name="course">
<option value="">Choose a course...</option>
<option value="html">HTML Fundamentals</option>
<option value="css">CSS Styling</option>
<option value="js">JavaScript Basics</option>
</select>
<!-- Radio buttons (single choice) -->
<fieldset>
<legend>Experience level</legend>
<label><input type="radio" name="level" value="beginner" /> Beginner</label>
<label><input type="radio" name="level" value="intermediate" /> Intermediate</label>
</fieldset>
<!-- Checkbox (multiple choices) -->
<label>
<input type="checkbox" name="newsletter" value="yes" />
Subscribe to updates
</label>
<!-- Textarea -->
<label for="message">Message</label>
<textarea id="message" name="message" rows="4" placeholder="Your message..."></textarea>
<!-- Submit -->
<button type="submit">Send Message</button>
</form>Every input should have a corresponding <label>. The for attribute on the label must match the id attribute on the input. This makes the label clickable (clicking it focuses the input) and is critical for accessibility.
| type | What it does |
|---|---|
| text | Single line of text |
| Email address (browser validates format) | |
| password | Hides the input characters |
| number | Numeric input with up/down arrows |
| tel | Phone number |
| url | Web address |
| date | Date picker |
| file | File upload |
| checkbox | Toggle on/off |
| radio | One choice from a group |
| range | A slider |
| submit | Submits the form |
TIP
Validation attributes. required makes a field mandatory. minlength and maxlength control text length. min and max work for numbers and dates. pattern accepts a regex pattern. These run before the form is submitted โ no JavaScript needed.