Problem Statement
How do you create a dropdown with grouped options?
Explanation
Creating a dropdown with grouped options involves using the optgroup tag within a select element to organize options into categories. This improves usability when you have many options that naturally fall into groups. The select tag creates the dropdown menu container. Inside select, you use option tags for individual choices. To group options, you wrap related option tags inside optgroup tags. The optgroup tag requires a label attribute that displays as a non-selectable heading in the dropdown. Users see the label but cannot select it. They can only select the options within each group. Multiple optgroups can exist in one select, each creating a distinct category. This hierarchical structure makes long dropdowns much easier to navigate. Common use cases include grouping countries by continent, organizing products by category, grouping files by type, or any data with natural categories. Benefits of grouped options include improved navigation, where users can quickly scan categories to find relevant options. Better organization makes the purpose of each option clearer through categorization. Enhanced usability helps when you have more than 15 to 20 options. Improved accessibility benefits screen reader users who hear the category labels. Visual hierarchy creates clear separation between groups in the dropdown. Best practices include using descriptive labels for optgroups that clearly indicate what the group contains. Keep groups logical and intuitive based on how users think about the options. Limit the number of groups to avoid overwhelming users, typically no more than five to seven groups. Within each group, keep similar numbers of options when possible. Place the most commonly used groups first. If an option does not fit any group, you can place ungrouped options before or after the optgroups. Always include a default option like Select a country at the top that prompts users to make a choice. The optgroup label attribute is required and should be a string. You cannot nest optgroups inside other optgroups. Modern browsers style optgroups with indentation and different font styling to make groups visually distinct. Understanding optgroups shows knowledge of creating user-friendly forms and is valuable for interviews about form design and usability.