How to Group Drop Down Form Elements into Categories
In this lesson you'll learn how to group drop down elements into organized categories for select boxes.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

In this video, we're going to see how to group elements together in a dropdown box.

Let's create a label and call it shipping_method. In general, never use spaces while naming your elements. Instead, use a snake case (which separates two words with an underscore) or camel case (where the second word starts with a capital letter with no space in between).

Next, let's create a dropdown box with the <select> tag. This tag will have no other attributes except name. Next, let's create groups with a tag called <optgroup>. This tag takes an attribute called label that should have a meaningful name. Inside this <optgroup> tag, we can create individual items with the <option> tag.

<label for="shipping_method">Shipping Method:</label>
<select name="shipping_method">
  <optgroup label="Business">
    <option value="biz_overnight">Overnight</option>
    <option value="biz_groung">Ground</option>
  </optgroup>
</select>

If you look at the output, you'll see that there is a label called "business", and options for it.

medium

You can create multiple groups like this:

<label for="shipping_method">Shipping Method:</label>
<select name="shipping_method">
  <optgroup label="Business">
    <option value="biz_overnight">Overnight</option>
    <option value="biz_groung">Ground</option>
  </optgroup>
  <optgroup label="Residential">
    <option value="res_overnight">Overnight</option>
    <option value="res_groung">Ground</option>
  </optgroup>
</select>

And the output will have two different groups.

medium

Ensure that each of these values has a unique name, as that's important from a script standpoint. For example, if you have a value "ground" for both business and residential, then the script will not know which option you've selected. This is why having a unique name is important.

So, this is how you can organize your options in a dropdown box.