// 選中項的文字
$("#ddlregtype").find("option:selected").text();
// 選中項的 value
$("#ddlregtype").val();
// 選中項的索引
$("#ddlregtype").get(0).selectedIndex;
// 依索引設定
$("#ddlregtype").get(0).selectedIndex = index;
// 依 value 設定
$("#ddlregtype").val("normal");
$("#ddlregtype").get(0).value = value;
// 依文字設定(需自行遍歷比對)
var count = $("#ddlregtype option").length;
for (var i = 0; i < count; i++) {
if ($("#ddlregtype").get(0).options[i].text == text) {
$("#ddlregtype").get(0).options[i].selected = true;
break;
}
}
$("#select_id option[text='jquery']").attr("selected", true);
$("#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
$("#ddlregtype").empty();
畫面上常見「左邊待選、右邊已選」的雙清單:
<div class="centent"> <select multiple="multiple" id="select1" name="dd" style="width:100px;height:160px;"> <option value="1">選項1</option> <option value="2">選項2</option> <option value="3">選項3</option> </select> <div> <span id="add">選中添加到右邊 >></span> <span id="add_all">全部添加到右邊 >></span> </div> </div> <div class="centent"> <select multiple="multiple" id="select2" name="sel" style="width:100px;height:160px;"></select> <div> <span id="remove"><< 選中刪除到左邊</span> <span id="remove_all"><< 全部刪除到左邊</span> </div> </div>
取得右邊 select 的值:
$(function () {
$('button').click(function () {
alert($('#select2').val()); // 取得 select2 目前的值
});
});
注意一個常見誤解:用 appendChild 或 append 把 option 從左邊搬到右邊時,元素是真的被搬移了,左邊的 select 裡已經沒有它。所以如果你寫成 $('#select1').each(...) 想取得搬走的項目,是取不到的。要取得右邊的內容,必須直接對 #select2 操作。
// 綁定上層下拉選單的 change 事件
$("#ClassLevel1").change(function () {
var id = $("#ClassLevel1").val();
var level2 = $("#ClassLevel2");
level2.empty(); // 先清空
$("#ClassLevel3").hide(); // 下下層先隱藏
$.ajax({
url: "./askCommon.ashx?action=getclasslevel&pid=" + id,
data: { "type": "ajax" },
dataType: "json",
type: "get",
success: function (data) {
var json = data; // dataType 為 json 時不需再 eval
for (var ind in json) {
level2.append($("<option value='" + json[ind].id + "'>" + json[ind].typename + "</option>"));
}
}
});
});
這裡有個重點:既然宣告了 dataType: "json",jQuery 已經幫你解析好了,不要再套 eval()。多一層 eval 不但多餘,還會在資料格式不如預期時直接讓腳本中斷。
上面用 attr("selected", true) 設定選中項,是 jQuery 1.6 之前的寫法。selected 與 checked 一樣屬於會變動的狀態,1.6 之後請改用 .prop("selected", true),否則在現代瀏覽器上可能無效。