How to Group HTML Select Options with optgroup

Grouping HTML select options is a great way to make the options available more readable to the user. In this tutorial, we will learn how to do this using the HTML optgroup tag.

 

The optgroup Syntax

The optgroup tag accepts two attributes on top of regular attributes such as classlabel and disabled.

 

<optgroup [label="Heading" disabled="true"]></optgroup>

 

  • label – the headline text for the group options
  • disabled – if set to true all the options within the group are disabled.

 

Splitting Up Select Options with optgroup Example

Let's say we had a bunch of dog and cat breeds for the user to choose from – it makes more sense to split them into different sections within the HTML select box. Here is an example of how to achieve that using the optgroup tag:

 

<label for="items">Choose an Animal:</label>
<select id="items">
   <optgroup label="Dogs">
       <option>Beagle</option>
       <option>Bulldog</option>
       <option>Golden Retriever</option>
   </optgroup>
   <optgroup label="Cats">
       <option>Bengal</option>
       <option>British Shorthair</option>
       <option>Burmese</option>
   </optgroup>

Conclusion

The optgroup tag is supported by all popular browsers.