How to Group Options in a Select Dropdown List CodeUnit 05 OCT 2011

The classic HTML select dropdown list box has been with us for a long time, consisting of a container <select> tag which in turn contains a number of <option> tags which make up the list items which the user can then choose one from.

If you have a number of options which can be logically grouped, then there is a further tag that you can make use of, namely the <optgroup> tag. This allows you to group related options by placing them in the <optgroup> container, which coincidently has a non selectable label to make the various group definitions easy to see in the eventual drop down list.

In practice, your HTML would look like this:

<select>
 
<optgroup label="Swedish Cars">
   
<option value="volvo">Volvo</option>
   
<option value="saab">Saab</option>
 
</optgroup>
 
<optgroup label="German Cars">
   
<option value="mercedes">Mercedes</option>
   
<option value="audi">Audi</option>
 
</optgroup>
</select>

Which would translate to this on your web page:

Supported by all major browsers, it certainly is a useful little tag to keep in the back of your mind. If you want more information on the <optgroup> tag, why don’t you pay a visit here?

About Craig Lotter

Software developer, husband and dad to two little girls. Writer behind An Exploring South African. I don't have time for myself any more.