下拉選單的讀取、設定、動態增刪,是表單開發的高頻操作。以下把常用語法整理成一份可直接複用的清單。
$("#select_id").change(function(){ /* 選擇其中一項時觸發 */ });
var checkText = $("#select_id").find("option:selected").text(); // 選中項的文字
var checkValue = $("#select_id").val(); // 選中項的 value
var checkIndex = $("#select_id").get(0).selectedIndex; // 選中項的索引
var maxIndex = $("#select_id option:last").attr("index"); // 最大索引值
$("#select_id").get(0).selectedIndex = 1; // 依索引設定
$("#select_id").val(4); // 依 value 設定
$("#select_id option[text='jQuery']").attr("selected", true); // 依文字設定
// 取得選中項的文字
$("#ddlRegType").find("option:selected").text();
// 取得選中項的 value
$("#nowamagic").val();
// 取得選中項的索引
$("#nowamagic").get(0).selectedIndex;
$("#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 的項
// 依索引
$("#nowamagic").get(0).selectedIndex = index;
// 依 value(三種寫法擇一)
$("#nowamagic").attr("value", "Normal");
$("#nowamagic").val("Normal");
$("#nowamagic").get(0).value = value;
依文字設定時沒有現成方法,需自行遍歷比對:
var count = $("#nowamagic option").length;
for (var i = 0; i < count; i++)
{
if ($("#nowamagic").get(0).options[i].text == text)
{
$("#nowamagic").get(0).options[i].selected = true;
break;
}
}
$("#nowamagic").empty();
幾個可以讓程式碼更乾淨的做法:
.val() 取代 .attr("value"),語意更清楚,也不必取 DOM 節點。.trigger("change"),因為程式設值不會自動觸發 change。$("<option>").val(v).text(t) 這種屬性式寫法,避免文字中的引號破壞 HTML。