Problem Statement
What is the purpose of the <optgroup> tag?
Explanation
The optgroup tag organizes options into categories within a dropdown select menu. When you have many options, grouping them makes the dropdown easier to navigate and understand. For example, grouping countries by continent or grouping products by category. The optgroup tag has a label attribute that displays as a non-selectable heading in the dropdown. Users cannot select the optgroup itself, only the options within it. This creates a visual hierarchy that helps users find what they need quickly. Optgroups improve user experience for long dropdown lists and are particularly useful for forms with geographic locations, product categories, or any hierarchical data. Screen readers announce the optgroup labels, improving accessibility.
Code Solution
SolutionRead Only
<!-- Dropdown with grouped options -->
<form>
<label for="location">Choose location:</label>
<select id="location" name="location">
<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="de">Germany</option>
<option value="fr">France</option>
</optgroup>
<optgroup label="Asia">
<option value="in">India</option>
<option value="jp">Japan</option>
<option value="cn">China</option>
</optgroup>
</select>
</form>
<!-- Product categories -->
<form>
<label for="product">Select Product:</label>
<select id="product" name="product">
<optgroup label="Electronics">
<option value="laptop">Laptop</option>
<option value="phone">Phone</option>
<option value="tablet">Tablet</option>
</optgroup>
<optgroup label="Clothing">
<option value="shirt">Shirt</option>
<option value="pants">Pants</option>
<option value="shoes">Shoes</option>
</optgroup>
</select>
</form>