下拉選單的操作可以歸成四類:加選項、刪選項、讀選項、設選項。以下把常用語法整理成可直接複用的清單。
$("#select_id").append("<option value='Value'>Text</option>");
// 在尾端追加一個選項
$("#select_id").prepend("<option value='0'>請選擇</option>");
// 在第一位插入
$("#select_id option:last").remove(); // 刪除最後一個
$("#select_id option[index='0']").remove(); // 刪除索引 0(寫法有問題,見下)
$("#select_id option[value='3']").remove(); // 刪除 value 為 3 的
$("#select_id option[text='4']").remove(); // 刪除文字為 4 的
$("#select_id").empty(); // 清空全部選項
option[index='0'] 這個寫法要修正。jQuery 沒有 index 這個屬性選擇器,正確寫法是 $("#select_id option:eq(0)").remove() 或 $("#select_id option").eq(0).remove()。:eq() 才是 jQuery 提供的索引篩選。
// 綁定 change 事件
$("#select_id").change(function () {
var text = $(this).find("option:selected").text(); // 文字
var value = $(this).val(); // 值
var index = $(this)[0].selectedIndex; // 索引
});
// 取得最大索引
var maxIndex = $("#select_id option:last").index();
注意最後一行:原範例寫 .attr("index"),但 option 元素上並沒有 index 屬性,這樣會得到 undefined。要取得位置請用 jQuery 的 .index() 方法。
$("#select_id").val("3"); // 依 value 選中
$("#select_id").val(""); // 取消選取(部分瀏覽器)
$("#select_id option[text='4']").attr("selected", "selected");
$("#select_id").prop("selectedIndex", 2); // 依索引選中
// 依文字選中:先找出對應的 value,再設值
var v = $("#select_id option").filter(function () {
return $(this).text() === "Text";
}).val();
$("#select_id").val(v);
// 單選
var v = $("#sel").val();
// 多選(同一 select 加了 multiple)
var arr = $("#sel").val(); // 回傳陣列
var arr2 = $("#sel").find("option:selected").map(function () {
return $(this).val();
}).get();
用 prop 而非 attr 處理 selected。與核取方塊同理,jQuery 1.6 之後 attr("selected") 只反映初始 HTML 屬性,不隨互動改變;要操作當前狀態請用 prop("selected", true)。
動態產生 option 時避免字串拼接。append("<option>" + 使用者輸入 + "</option>") 有 XSS 風險。改用屬性設定式寫法:
$newOpt = $('<option>', { value: id, text: name });
$("#sel").append($newOpt);
另外,清空並重建選項後若原本綁了 change 事件,替換元素會一併丟掉監聽,改用事件委派 $(document).on('change', '#sel', fn) 就不受影響。