在 ASP.NET 專案中,常需要在用戶切換下拉選單時立即取得當前的值與顯示文字。做法是透過 selectedIndex 定位選中項,再從 options 集合中讀取 value 與 text。
<script type="text/javascript" language="javascript">
function SearchChange(){
var ddl = document.getElementById("DropDownList1");
var index = ddl.selectedIndex;
var Value = ddl.options[index].value;
var Text = ddl.options[index].text;
alert(Value);
}
</script>
<asp:DropDownList ID="DropDownList1" runat="server"
onchange="SearchChange();">
<asp:ListItem Value="0">111</asp:ListItem>
<asp:ListItem Value="1">222</asp:ListItem>
<asp:ListItem Value="2">333</asp:ListItem>
</asp:DropDownList>
ASP.NET 伺服器控制項最終會被渲染成標準的 <select>,且 ID 可能被加上 ClientID 前綴(例如 ctl00_ContentPlaceHolder1_DropDownList1)。若直接用 getElementById("DropDownList1") 取不到元素,應改用 document.getElementById('<%= DropDownList1.ClientID %>')。
如果希望每次變更都觸發,且控制項宣告時帶有 runat="server",要留意 onchange 屬性在部分情況下需寫為 onchange 對應的用戶端事件,避免與 AutoPostBack 互相覆蓋。
取得 text 時若想同時拿到多個選項,可改用 ddl.options 搭配迴圈遍歷,而不只依賴單一 selectedIndex。