DIV CSS 佈局教程網

JavaScript 取得 DropDownList 選中項的 value 與 text
編輯:關於JavaScript     

在 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。

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