Topic 26 of 41
Selection Controls
Overview
When you need a user to select from a strict, predefined set of options, freeform text inputs invite catastrophic typos (e.g., typing 'Texus' instead of 'Texas'). HTML provides Checkboxes (for selecting multiple overlapping options), Radio Buttons (for selecting exactly one mutually exclusive option from a list), and Select Dropdowns (for selecting one option from a massive list).
Syntax
html
<!-- 1. Checkboxes (Multiple choices allowed) -->
<label>
<input type="checkbox" name="interests" value="coding" checked> Coding
</label>
<label>
<input type="checkbox" name="interests" value="music"> Music
</label>
<!-- 2. Radio Buttons (Mutually exclusive - MUST share the same 'name'!) -->
<label>
<input type="radio" name="subscription" value="free" checked> Free Plan
</label>
<label>
<input type="radio" name="subscription" value="pro"> Pro Plan ($10)
</label>
<!-- 3. Select Dropdown (Best for massive lists) -->
<label for="country">Country:</label>
<select name="country" id="country">
<option value="">-- Choose --</option>
<option value="US">United States</option>
<option value="UK">United Kingdom</option>
</select>Common Pitfalls
- Forgetting to give all Radio buttons in a group the exact same
nameattribute. Without a matchingname, the browser doesn't know they belong together, allowing the user to select ALL of the mutually exclusive options simultaneously. - Omitting the
valueattribute on checkboxes and radios. If you don't provide avalue, the browser simply submitsinterests=onto the server, providing zero context about which specific box was actually checked.
Interview Questions
Q:
How do you group options inside a massive
<select> dropdown to make it more readable?A:
By using the <optgroup> tag. You wrap related <option> tags inside <optgroup label="North America">, and the browser will automatically render a non-clickable, bolded category header in the dropdown.
Real-World Example
A disabled select dropdown that forces the user to choose an option before proceeding.
example
html
<!-- By making the placeholder disabled and hidden, it forces a real choice -->
<select name="tier" required>
<option value="" disabled selected hidden>Select your pricing tier...</option>
<option value="basic">Basic ($9)</option>
<option value="pro">Pro ($29)</option>
</select>Check Your Knowledge
Test your understanding of Selection Controls with these quick questions.