Grouping Options with <optgroup>
You'll learn how to organize long dropdown lists into labeled sections, making forms easier to scan and use.
When you have a <select> dropdown with many options, users can get overwhelmed scrolling through an endless list. The <optgroup> element lets you group related options under descriptive headings—like creating categories in a menu.
The Core Idea
Think of a restaurant menu: instead of listing 50 dishes randomly, you see sections like "Appetizers," "Main Courses," and "Desserts." That's exactly what <optgroup> does for your select dropdowns.
The <optgroup> element wraps around related <option> elements and uses a label attribute to display the group heading. The heading itself isn't selectable—it's just a visual organizer.
How to Use It
<select name="country">
<optgroup label="North America">
<option value="us">United States</option>
<option value="ca">Canada</option>
<option value="mx">Mexico</option>
</optgroup>
<optgroup label="Europe">
<option value="uk">United Kingdom</option>
<option value="fr">France</option>
<option value="de">Germany</option>
</optgroup>
</select>
In the browser, users will see "North America" and "Europe" as non-clickable headings, with the actual countries indented beneath them. This makes scanning a list of dozens (or hundreds) of countries far more manageable.
You can mix grouped and ungrouped options in the same <select>, though it's clearer to be consistent.
Key Takeaway: Use <optgroup label="..."> to organize long dropdown lists into labeled sections, dramatically improving usability and making it easier for users to find the option they need.