JavaScriptを用いて、selectボックスを動的に作成するサンプル
(参考:
http://blog.gridworlds.com/js/how-to-create-optgroups-in-javascript)
1.オプショングループの作成
// オブジェクト作成
var asagohan = document.createElement("optgroup");
// ラベルの設定
asagohan.label = "朝ごはん";
2.オプションの作成
// オブジェクト作成
var siriaru = document.createElement("option");
// value値の設定
siriaru.value = "siriaru";
// 画面上に表示される選択文字列の設定
siriaru.appendChild(document.createTextNode("シリアル"));
// オプショングループに追加
asagohan.appendChild(siriaru);
3.選択済み項目の設定(必要に応じて)
siriaru.selected = true;
4.selectボックスクリア
// selectボックスを取得
var selectMenu = document.getElementById("foodOptions");
// 子要素がある分だけ除去
while (selectMenu.hasChildNodes()) {
selectMenu.removeChild(selectMenu.firstChild);
}
5.オプショングループ追加
// 子要素を保持しているオプショングループオブジェクトをselectボックスに追加
if (asagohan.hasChildNodes()) { selectMenu.appendChild(asagohan); }
if (lunch.hasChildNodes()) { selectMenu.appendChild(lunch); }
if (dinner.hasChildNodes()) { selectMenu.appendChild(dinner); }