Skip to main content

HTML Tags

HTML <optgroup> Tag

Written by Updated HTML <optgroup> Tag exercises

The optgroup tag puts headings inside a long drop-down list, like "Fruits" and "Vegetables", with the options for each group under its heading. The headings themselves cannot be chosen.

It goes inside a select and wraps option elements.

Syntax

html

<optgroup label="Group Name" disabled>
  <option value="value1">Option 1</option>
  <option value="value2">Option 2</option>
</optgroup>
AttributeWhat it does
labelThe heading shown for the group. Required.
disabledGreys out the whole group; none of its options can be chosen.

Example

html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Optgroup Example</title>
</head>
<body>
  <h2>Select a Fruit or Vegetable</h2>
  <form action="/samples/form_processor.php" method="post">
    <label for="items">Choose an item:</label><br>
    <select name="items" id="items" required>
      <optgroup label="Fruits">
        <option value="apple">Apple</option>
        <option value="banana">Banana</option>
      </optgroup>
      <optgroup label="Vegetables">
        <option value="carrot">Carrot</option>
        <option value="spinach">Spinach</option>
      </optgroup>
      <optgroup label="Unavailable" disabled>
        <option value="tomato">Tomato</option>
      </optgroup>
    </select><br><br>

    <input type="submit" value="Submit">
  </form>
</body>
</html>

The drop-down shows "Fruits" and "Vegetables" as bold headings, each with its options indented below. The "Unavailable" group is greyed out because it is disabled.

Browser Support

Chrome
Edge
Firefox
Safari
Opera
IE9+
YesYesYesYesYesYes

Good to know

  • Groups cannot be nested. One level of headings is all a select supports.
  • The label is announced by screen readers along with each option, so keep it short.
  • Use groups when a list is long enough that headings help people scan it. A list of five options does not need them.

HTML <optgroup> Tag exercises

Group two options

Add a dropdown named city with one group labelled India that holds Delhi (del) and Pune (pnq).

Result

Check your answer to see it here.