Select 下拉選單是表單開發中再常見不過的元素,無論是讀取選中項、設定選中狀態,還是動態增刪選項,都很常派上用場。本文把 jQuery 操作 select 的常見技巧整理成一份 handy 的速查表。
取得選中項的文字:
$("#cusChildTypeId").find("option:selected").text();
$("#cusChildTypeId option:selected").text()
取得選中項的值:
$("#ddlRegType").val();
取得選中項的索引:
$("#ddlRegType").get(0).selectedIndex;
取得選項總數:
$("#cusChildTypeId").get(0).options.length
依索引設定:
$("#cusChildTypeId").get(0).selectedIndex = index;
依 value 設定:
$("#cusChildTypeId").attr("value","Normal");
$("#cusChildTypeId").val("Normal");
$("#cusChildTypeId").get(0).value = "Normal";
依 text 設定:可先遍歷 options 比對文字,命中後將該項的 selected 設為 true;或直接 $("#cusChildTypeId").val(text); 後觸發 change()。
新增一項(顯示 text、值為 value):
$("#cusChildTypeId").get(0).options.add(new Option(text,value));
刪除值為 value 的項:先取得 options.length,再以迴圈比對每個 option 的 value,命中後呼叫 $("#cusChildTypeId").get(0).remove(i); 並 break 跳出。
清空整個 select:
$("#cusChildTypeId").empty();
$("#cusChildTypeId").get(0).options.length = 0;
這些方法幾乎涵蓋了日常 90% 的 select 操作場景。建議把這份清單收藏起來,日後開發時翻一翻就能快速上手。