ProblemYou want to group related choices logically on a form. SolutionUse the <optgroup> element to create groups of similar options within one select menu. <select name="name"> <optgroup label="label"> <option label=" label "value="value"> label </option> <option label="label " value="value"> label </option> </optgroup> </select> DiscussionIn a simple select menu, the options are listed together within the <select> element. Adding the <optgroup> element offers a way for you to group sub-lists of options hierarchically so the menu choices appear more clearly to the user. There's no limit to the number of <options> that can be listed within an <optgroup>, and no limit to the number of <optgroups> that can be included in one list. You also can display one or many options on the page (using the size attribute) and allow the user to select more than one option by adding the multiple attribute to the <select> element (see Figures 8-6 and 8-7). Figure 8-6. The <optgroup> values in this select menu (Small, Medium, etc.) are not selectable themselves, but serve to organize the <option> values indented and listed beneath themFigure 8-7. Adding the size attribute to a select menu with five <optgroup> elements causes the entire menu to be displayed in the browser, rather than requiring the user to click the menu so it pops up into view
As the example in Figure 8-6 demonstrates, menus using the <optgroup> element are useful when the visitors must select two related options on a form, such as the size and color of an item they want to purchase from your online store. Other potential uses for you to consider include location information (grouped by state, then city), membership or subscription plans (grouped by level of service, then length of service), or ticket orders for performances (grouped by date, then time). See AlsoRecipe 7.5 |