HTML optgroup Tag Tutorial

In this section, we will learn what HTML <optgroup> is and how to use it.

What is <optgroup> Tag in HTML?

HTML <optgroup> element stands for option group and is used to group the items in a dropdown list created by HTML <select> element and can set a header for those groups.

For example, let’s say you have a list and the items are different brands of cars and you want to group these items based on the country that each brand belongs to. So you can use the <optgroup> element to group those items that are of the same country and then set a header for that group mentioning the country’s name.

HTML <optgroup> Tag Syntax:

<optgroup>

<option> </option>

<option> </option>

<option> </option>

</optgroup>

HTML <optgroup> Tag Values

The value we set for the <optgroup> element (in its body) is one or more <option> elements that we want to group them together.

Example: using <optgroup> tag in HTML

See the Pen using <optgroup> tag in HTML by Omid Dehghan (@odehghan) on CodePen.

HTML <optgroup> Tag Attributes

HTML <optgroup> element has two attributes:

Name

Description

disabled

Using this attribute, we can disable a group of options. This means no option in that group can be selected after applying this attribute.

label

Using this attribute, we can set a text content to appear as the header of the grouped options.

What is disabled Attribute in HTML <optgroup> Tag?

We use the disabled attribute when we want to disable the use of items in an <optgroup> so that users can’t pick from that group anymore.

HTML disabled Attribute in <optgroup> Tag Syntax:

<optgroup disabled> </optgroup>

<optgroup> Tag disabled Attribute Values

The disabled attribute is a boolean attribute and so we only need to put that attribute in the opening tag of the <optgroup> element. After that, the entire items in that group become disabled.

Example: using disabled attribute in HTML <optgroup> tag

See the Pen using disabled attribute in HTML <optgroup> tag by Omid Dehghan (@odehghan) on CodePen.

What is label Attribute in HTML <optgroup> Tag?

The label attribute is used to set a header for a group created via <optgroup> element.

Users will then see the value of this attribute as the header for that group.

HTML label Attribute in <optgroup> Tag Syntax:

<optgroup label = “header-value”> </optgroup>

<optgroup> Tag label Attribute Values

The value we set for the label attribute is the value we want users to see as the header for a group of items on a dropdown list.

Example: using label attribute in HTML <optgroup> tag

See the Pen label attribute in HTML <optgroup> tag by Omid Dehghan (@odehghan) on CodePen.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies