The <optgroup>
tag is used to group related options in a drop-down list. It is a child element of the <select>
tag and can contain one or more <option>
tags.
The <optgroup>
tag is useful when you have a long list of options and want to group them into categories. For example, if you have a list of countries, you could group them by continent using the <optgroup>
tag.
The <optgroup>
tag has two attributes:
label
: Specifies the label for the group of options.disabled
: Specifies that the group of options should be disabled.The label
attribute is required and should be a text string that describes the group of options. The disabled
attribute is optional and should be used when you want to disable the entire group of options.
Here is an example of how to use the <optgroup>
tag:
<select> <optgroup label="Europe"> <option value="france">France</option> <option value="germany">Germany</option> <option value="italy">Italy</option> </optgroup> <optgroup label="Asia"> <option value="china">China</option> <option value="japan">Japan</option> <option value="korea">Korea</option> </optgroup> </select>
In this example, we have two groups of options: one for Europe and one for Asia. Each group is labeled using the label
attribute, and contains several <option>
tags.
If you want to disable a group of options, you can add the disabled
attribute to the <optgroup>
tag:
<select> <optgroup label="Europe" disabled> <option value="france">France</option> <option value="germany">Germany</option> <option value="italy">Italy</option> </optgroup> <optgroup label="Asia"> <option value="china">China</option> <option value="japan">Japan</option> <option value="korea">Korea</option> </optgroup> </select>
In this example, the group of options for Europe is disabled, which means that the user cannot select any of the options in that group.
Here are some more examples of how to use the <optgroup>
tag:
<select> <optgroup label="Fruits"> <option value="apple">Apple</option> <option value="banana">Banana</option> <option value="orange">Orange</option> </optgroup> <optgroup label="Vegetables"> <option value="carrot">Carrot</option> <option value="celery">Celery</option> <option value="broccoli">Broccoli</option> </optgroup> </select>
<select> <optgroup label="Colors"> <option value="red">Red</option> <option value="green">Green</option> <option value="blue">Blue</option> </optgroup> <optgroup label="Shapes"> <option value="circle">Circle</option> <option value="square">Square</option> <option value="triangle">Triangle</option> </optgroup> </select>
<select> <optgroup label="Animals"> <option value="dog">Dog</option> <option value="cat">Cat</option> <option value="bird">Bird</option> </optgroup> <optgroup label="Insects"> <option value="ant">Ant</option> <option value="bee">Bee</option> <option value="spider">Spider</option> </optgroup> </select>