DIV CSS 佈局教程網

jQuery 操作 select 下拉選單:取值與 option 增刪
編輯:JQuery特效代碼     

下拉選單是表單中不可或缺的元素,無論是取值、設定選中項,還是動態增刪選項,jQuery 都能優雅處理。以下把常用操作整理成一份速查表。

取得選中的 Text 與 Value

$("#select_id").change(function(){//為 Select 添加事件,選擇時觸發
var checkText=$("#select_id").find("option:selected").text(); //取得選中的 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; //設定索引值為 1 的項選中
$("#select_id").val(4); //設定 Value 為 4 的項選中
$("#select_id option[text='jQuery']").attr("selected", true); //設定 Text 為 jQuery 的項選中

新增與刪除 option

$("#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(); //刪除 Text 為 4 的選項

清空下拉選單

$("#ddlRegType").empty();

取值與設值補充

取得選中的 text:$("#ddlRegType").find("option:selected").text();

取得選中的 value:$("#ddlRegType").val();

取得選中的索引:$("#ddlRegType").get(0).selectedIndex;

依 text 設定選中項,需要搭配迴圈比對:

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;
}
}

掌握這些語法,就能靈活應對絕大多數的下拉選單操作場景,例如三、四級聯動分類就是典型應用。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved