在 Web 開發中,下拉選單是常見的表單元素。本文系統整理 jQuery 獲取、設置、增刪 Option 的實用代碼片段,幫助開發者快速掌握核心操作。
// 綁定 change 事件
$("#select_id").change(function() {
// 獲取選中項的顯示文本
var checkText = $("#select_id").find("option:selected").text();
// 獲取選中項的 value 值
var checkValue = $("#select_id").val();
// 獲取選中項的索引(從 0 開始)
var checkIndex = $("#select_id").get(0).selectedIndex;
// 獲取最大索引值
var maxIndex = $("#select_id option:last").attr("index");
});
// 1. 指定索引選中
$("#select_id").get(0).selectedIndex = 1;
// 2. 指定 value 值選中
$("#select_id").val(4);
// 3. 指定顯示文本選中
$("#select_id option[text='jQuery']").attr("selected", true);
// 追加到末尾
$("#select_id").append("");
// 插入到最前面
$("#select_id").prepend("");
// 刪除最後一項
$("#select_id option:last").remove();
// 刪除索引為 0 的項
$("#select_id option[index='0']").remove();
// 刪除指定 value 的項
$("#select_id option[value='3']").remove();
// 刪除指定文本的項
$("#select_id option[text='4']").remove();
// 清空所有選項
$("#ddlRegType").empty();
當用戶選擇三級分類時,自動清空四級分類的非默認項:
if ($("#thirdLevel").val() != 0) {
$("#thirdLevel option[value!=0]").remove();
}
if ($("#fourthLevelId").val() != 0) {
$("#fourthLevelId option[value!=0]").remove();
}
// Radio 獲取選中值
var radioVal = $('input:radio[name="sex"]:checked').val();
// Checkbox 獲取所有選中值
var chkValues = [];
$('input[name="checkbox"]:checked').each(function() {
chkValues.push($(this).val());
});
掌握這些核心 API,即可輕鬆應對各類下拉選單交互需求。