The `<optgroup>` tag is an HTML element used to group related options within a select menu. This element is often used in conjunction with the `<select>` tag to create dropdown menus with multiple categories of options.
Here’s a step-by-step tutorial on how to use the `<optgroup>` tag:
Step 1: Create a `<select>` element
The first step is to create a select element that will contain the options you want to group. You can create a select element using the following code:
<select>
<!– options go here –>
</select>
Step 2: Add `<optgroup>` elements
Next, you’ll want to add `<optgroup>` elements inside the `<select>` element to group your options. Here’s an example:
<select>
<optgroup label=”Group 1″>
<option value=”option1″>Option 1</option>
<option value=”option2″>Option 2</option>
</optgroup>
<optgroup label=”Group 2″>
<option value=”option3″>Option 3</option>
<option value=”option4″>Option 4</option>
</optgroup>
</select>
In this example, we have two `<optgroup>` elements, each with a `label` attribute that specifies the name of the group. Inside each `<optgroup>` element, we have two `<option>` elements.
Step 3: Add `value` attributes to options
Each option should have a `value` attribute that specifies the value that will be sent to the server if the option is selected. Here’s an example:
<select>
<optgroup label=”Group 1″>
<option value=”option1″>Option 1</option>
<option value=”option2″>Option 2</option>
</optgroup>
<optgroup label=”Group 2″>
<option value=”option3″>Option 3</option>
<option value=”option4″>Option 4</option>
</optgroup>
</select>
In this example, the `value` attributes of the options are “option1”, “option2”, “option3”, and “option4”.
Step 4: Add styling (optional)
You can add styling to your `<optgroup>` elements using CSS. Here’s an example:
optgroup {
font-weight: bold;
color: blue;
}
In this example, we’re using CSS to make the text inside `<optgroup>` elements bold and blue.
That’s it! By following these steps, you can create dropdown menus with grouped options using the `<optgroup>` tag.