Search this blog


Home About Contact
2009年10月18日星期日

Use the optgroup element to group select options  

Sometimes it is useful to group the options of an HTML select element. Many developers use extra option elements and non-breaking spaces to create the visual appearance of hierarchical options, but there is another way: the often forgotten optgroup element.

To create a group of options, wrap them in an optgroup element. To give the group a label, use the label attribute. Here is a simple example:

  1. <label for="cars">Choose a car brand:</label>
  2. <select name="cars" id="cars">
  3. <option value="none" selected>None</option>
  4. <optgroup label="Swedish">
  5. <option value="saab">Saab</option>
  6. <option value="volvo">Volvo</option>
  7. </optgroup>
  8. <optgroup label="French">
  9. <option value="citroen">Citroën</option>
  10. <option value="peugeot">Peugeot</option>
  11. <option value="renault">Renault</option>
  12. </optgroup>
  13. </select>

And here is how the browser you are currently using will render the above example:

One caveat is that assistive technology support for the optgroup element and the label attribute is inconsistent, as noted in Creating Accessible Forms at WebAIM and the WCAG 2 technique H85: Using OPTGROUP to group OPTION elements inside a SELECT.

This post is a Quick Tip. Background info is available in Quick Tips for web developers and web designers.

Posted in , , .


What next?

You can also bookmark this post using your favorite bookmarking service:

Related Posts by Categories