下拉選單的動態操作——新增、刪除、取值、取索引、綁定事件——是表單開發中的高頻需求。本文把原生 JavaScript 與 jQuery 兩套寫法並列整理,方便查閱。
var obj = document.getElementById(selectid);
obj.options.length = 0; // 清空所有選項
obj.options[index] = new Option("three", 3); // 變更對應位置的 option
obj.options[index].selected = true; // 保持選中狀態
obj.add(new Option("4", "4")); // 新增選項,參數依序為「文字」與「值」
var index = obj.selectedIndex;
obj.options.remove(index); // 刪除選中項
// 為 Select 追加一個 option
$("#select_id").append("<option value='Value'>Text</option>");
// 取得選中項的 text 與 value
$("#select_id").find('option:selected').text();
$("#select_id").val();
// 刪除指定條件的 option
$("#select_id option[index='0']").remove(); // 刪除索引為 0 的選項
$("#select_id option[value='3']").remove(); // 刪除值為 3 的選項
$("#select_id option[text='4']").remove(); // 刪除文字為 4 的選項
// 綁定 change 事件
$("#select_id").change(function () {
// 在這裡撰寫需要執行的操作
});
原生寫法其實有固定的三步,把它記牢就幾乎能應付所有情境:
var obj = document.getElementById("testSelect"); // 定位元素
var index = obj.selectedIndex; // 選中項的索引
var text = obj.options[index].text; // 選中項的文字
var value = obj.options[index].value; // 選中項的值
第一種方式
$('#testSelect option:selected').text(); // 選中的文字
$('#testSelect option:selected').val(); // 選中的值
$("#testSelect").get(0).selectedIndex; // 選中的索引
第二種方式
$("#testSelect").find("option:selected").text(); // 選中的文字
// .val() 取得值、.get(0).selectedIndex 取得索引
jQuery 的 val() 在單選時回傳字串,在多選(加上 multiple 屬性)時則回傳陣列,取值後記得依情況處理型別。另外,用 append 動態插入 HTML 字串時,若文字內容來自使用者輸入,建議改用 new Option 或先跳脫,以避免 XSS 風險。