セレクトボックスの操作
arthur
前提
セレクトボックスは以下のように定義されているものとする。
<select id="my-select">
</select>
項目の追加
const select = document.getElementById('my-select');
const newOption = document.createElement('option');
newOption.value = '1'
newOption.text = 'One'
select.appendChild(newOption)
項目の削除
const select = document.getElementById('my-select');
while(select.children.length > 0) {
select.removeChild(select.lastChild);
}
先頭の要素だけ残してその他の項目を削除
先頭に「選択してください」のような固定の要素がある場合はこの方法を使う。
const select = document.getElementById('my-select');
while(select.children.length > 1) {
select.removeChild(select.lastChild);
}
特定の条件を満たす要素だけを削除
直感的には先頭から調べたいところだが、後ろから検証して削除する。
先頭から調べた場合、削除した分要素番号がずれるため、スキップされる要素が出てきてしまう。
const select = document.getElementById('my-select');
for(let i = select.options.length - 1; i > 0; i--) {
const option = select.options[i];
if(option.value.includes('削除')) {
select.remove(i);
}
}
項目の選択
先頭の要素を選択
const select = document.getElementById('my-select');
select.selectedIndex = 0;
特定の値を持った要素を選択したい場合
select.valueに代入する値は選択したい項目のvalueを設定する。以下の例の場合、valueが空文字の項目が選択される。
const select = doucment.getElementById('my-select');
select.value = '';
複数選択可能としている場合に先頭項目のみ選択させたい
複数選択可能な場合、以下のコードで先頭要素のみを選択した状態にできる。すべての選択を解除したい場合は単純にfalseを代入すればよい。
const select = document.getElementById('my-select');
Array.from(select.options).forEach((opt, index) => {
opt.selected = (index === 0);
});
選択された値の取得
選択できるのが1項目の場合
const select = document.getElementById('my-select');
// 選択した項目のvalueだけ取得できれば良い場合
const selectedValue = select.value;
// 選択した項目のテキストも取得したい場合
const selectedOption = select.options[select.selectedIndex];
複数選択可能な場合
const select = document.getElementById('my-select');
const selectedValues = Array.from(select.selectedOptions).map(opt => opt.value);
onChangeイベント
無名関数を定義する場合
document.getElementById('my-select).addEventListener('change', (e) => {
// 処理を書く
});
HTMLで定義する場合
<select id="my-select" onChange="handleMySelectOnChange()">
</select>
ABOUT ME