Using optgroup to group options in an HTML select box
Posted May 9th, 2009 in HTML and CSS
Following on with my current theme of looking at some useful form tags in HTML (last week I looked at fieldset and legend and the week before at label) this week's HTML post will look at using the optgroup tag to group options together in a select box.
First, an example to show what I'm talking about:
If you open up the select box you'll see that there are two groups of options labelled "Fruit" and "Veges". Depending on the browser you are using, this will be bold+italic, bold, background bold etc, but in same way made to look like a heading and it is not selectable. The options under the group name is indented and not bold.
Here's the HTML behind the select box above:
<form>
What is your favorite food?<br />
<select name="food">
<option></option>
<optgroup label="Fruit">
<option>Apples</option>
<option>Bananas</option>
<option>Oranges</option>
</optgroup>
<optgroup label="Veges">
<option>Beans</option>
<option>Carrots</option>
<option>Peas</option>
</optgroup>
</select>
</form>
The "label" property of the <optgroup> tag is what appears as the heading for the group of options.
It's possible to style the optgroup with CSS but I'll look at that in next week's HTML/CSS post.
Related posts:
- Style HTML form elements optgroup and option with CSS in Firefox (Saturday, May 16th 2009)
- Fieldset and legend tags in HTML forms (Saturday, May 2nd 2009)
- Using the <label> tag for HTML forms (Saturday, April 25th 2009)
- Switch off autocomplete for an HTML form field (Saturday, December 6th 2008)
- Style an HTML form input with CSS and jQuery (Saturday, July 26th 2008)

Comments
blog comments powered by Disqus