取得下拉選單(select)中被選中選項的文字,方法有很多,本文示範用原生 JavaScript 分三個步驟輕鬆完成。
var sel = document.getElementById(id); // 取得 select 元素 var index = sel.selectedIndex; // 取得被選中 option 的索引 var textsel = sel.options[index].text; // 取得對應 option 的文字內容
getElementById 抓出目標 select。selectedIndex 會回傳目前選中選項的索引位置。text 屬性,就是使用者看到的文字。別把 text 與 value 搞混了。option 上的 text 是「使用者看到的顯示文字」,而 value 則是「送給伺服器的實際值」,兩者可以不同。若你要的是送出的值,把最後一行的 .text 換成 .value 即可:
var value = sel.options[sel.selectedIndex].value;
理解這個差異,取值時就不會拿錯了。