← All writing
Craft · · 1 min

optgroup

HTML Forms Small Print

A client’s shipping form had a country list with about 200 entries in it and their five actual markets buried somewhere in the alphabet.

The fix is one element.

country.html
<select name="country">
  <optgroup label="Where we ship">
    <option>United States</option>
    <option>Canada</option>
  </optgroup>
  <optgroup label="Everywhere else">
    <option>Afghanistan</option>
  </optgroup>
</select>
HTML

<optgroup> puts a non-selectable heading above a run of options. It is styled by the browser, differently in each one. You get very little say about that. It cannot nest, so there are exactly two levels available and the second one is all you get.

That is the whole element. I bring it up because the alternative I keep finding in the wild is a disabled <option> with dashes typed around it, which is somebody reinventing this without knowing it existed. The dashes version is announced as an option that happens to be unavailable. This one is announced as a group label, which is what it is.

Reach for it any time a list has natural sections. It costs nothing and it turns a scroll into a scan.

Read similar posts
2 min

fieldset and legend

A group of radio buttons has a question attached to it, and the question needs to be in the markup rather than in a heading that happens to sit nearby.

8 min

Scroll wheels and zip codes

A customer was charged for 40 of something they had ordered 4 of, and the mechanism turned out to be a browser behavior sitting inside the one input type everybody reaches for.