下拉選單的動態操作是表單開發的常°:新增選項、讀取目前選取值、清空或刪除特定項目。以下把常用語法整理成可直接參照的片段。
var Select1 = document.getElementById("Select1");
// 寫法一:指定索引位置
Select1.options[0] = new Option('a', '0');
// 寫法二:使用 add 方法
Select1.options.add(new Option('a', '0'));
寫法一中的 options[0] 的 0 是索引,能精準控制插入位置,彈性略勝一籌。
// 取得目前選項的 value
var v = Select1.value;
// 取得目前選項顯示的文字
var t = Select1.options[Select1.selectedIndex].text;
// 也可分別取得
Select1.options[Select1.selectedIndex].value
Select1.options[Select1.selectedIndex].text
// 一次清空所有選項
Select1.options.length = 0;
// 刪除指定索引的單一選項
Select1.options.remove(indx);
Select1.value = 某個值;
補充一個實務上更嚴謹的寫法:直接設 select.value 時,若該值在選項中不存在,瀏覽器不會報錯,只會讓選單回到無選取的狀態。因此若是從外部資料回填,建議先比對再決定要不要設值,例如用 [...Select1.options].some(o => o.value === target) 確認存在,再進行指派,能避免畫面顯示空白卻毫無提示的狀況。