當 <select> 的選項多到二三十個,使用者往往找不到自己要的那一項。這時候可以用 optgroup 標籤把選項分組,讓下拉式選單出現清楚的分類標題,選單的可用性會立刻提升不少。
<select>
<optgroup label="分類名稱">
<option>項目一</option>
<option>項目二</option>
</optgroup>
</select>
label 屬性會成為該分類的顯示名稱,而 <option> 則是被歸在同一組裡的實際選項。經測試,IE 與 Firefox 都能正確支援這個標籤。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"https://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title>runcode</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="Author" content="Sheneyan" />
</head>
<body>
<select>
<optgroup label="a">
<option>a1</option>
<option>a2</option>
<option>a3</option>
</optgroup>
<optgroup label="b">
<option>b1</option>
<option>b2</option>
<option>b3</option>
</optgroup>
</select>
</body>
</html>
optgroup 最適合用在有明顯層級關係的資料上,例如「地區 → 城市」、「類別 → 品項」。分類名稱要簡短,組數建議控制在五組以內,否則分組反而變成另一種混亂。若再為 <option> 加上 value 屬性,送表單時也更容易對應後端資料。