HTML Tutorial

HTML Tag: <optgroup>

Usage

The <optgroup> tag groups related options within a <select> element. It's used to organize and categorize options, making it easier for users to navigate a large list of choices.

Attributes

  • label: Specifies the label for the optgroup.
  • disabled: Disables all options within the optgroup.

Examples

<!-- Basic optgroup -->
<select>
  <optgroup label="Colors">
    <option value="red">Red</option>
    <option value="blue">Blue</option>
    <option value="green">Green</option>
  </optgroup>

  <optgroup label="Shapes">
    <option value="circle">Circle</option>
    <option value="square">Square</option>
    <option value="triangle">Triangle</option>
  </optgroup>
</select>

<!-- Disabled optgroup -->
<select>
  <optgroup label="Disabled" disabled>
    <option value="disabled1">Disabled Option 1</option>
    <option value="disabled2">Disabled Option 2</option>
  </optgroup>
</select>

Exploring the <optgroup> Tag

  1. Create a <select> element and add some <option> elements.
  2. Add one or more <optgroup> elements within the <select> element.
  3. Set the label attribute on each <optgroup> to specify its label text.
  4. If needed, set the disabled attribute on <optgroup> to disable all options within that group.

Improved Accessibility and Ease of Use

  • Group related options to make it easier for users to find and select the most relevant choice.
  • Use the label attribute to provide clear and descriptive text for each optgroup, aiding screen readers and improving user comprehension.
  • Disable optgroups when necessary to prevent users from selecting invalid or unavailable options.