在做表單或互動介面時,經常需要讀取使用者在下拉選單(Select)中選了哪一個選項。本文整理了一套在 IE、Firefox、Opera、Chrome 等主流瀏覽器都能正常運行的寫法,簡單易用,適合直接套用到專案裡。
Select 元件底層其實就是一個 options 集合,每個 option 都帶有 value(提交給後台的值)與 text(頁面上顯示的文字)。只要先取得目前被選中的索引 selectedIndex,再透過 options 陣列取出對應的項目即可。
下列兩行程式分別取得「值」與「顯示文字」:
var value = document.getElementById("select").options[document.getElementById("select").options.selectedIndex].value;
var text = document.getElementById("select").options[document.getElementById("select").options.selectedIndex].text;
以下範例在點擊按鈕後,會跳出目前選中選項的值:
<script>
function check() {
var select = document.getElementById("select").options[document.getElementById("select").options.selectedIndex].value;
alert(select);
}
</script>
<select name="select" id="select">
<option value="test1" selected="selected">Test1</option>
<option value="test2">Test2</option>
</select>
<input type="button" value="我要試試" onclick="check()" />
除了上述逐層取值的做法,其實也可以直接透過被選中的 option 元素來取值,程式碼更直觀:
var sel = document.getElementById("select");
var value = sel.options[sel.selectedIndex].value;
var text = sel.options[sel.selectedIndex].text;
這兩種方式在現代瀏覽器中都能保持一致行為,可依個人習慣挑選。掌握 selectedIndex 這個關鍵屬性,就能輕鬆讀取下拉選單的目前狀態。