不靠任何函式庫,只用原生 JavaScript 讀取 select 目前選中的選項,其實只要一行就足夠。這篇用一個可直接跑起來的最小範例說明。
var sel = document.getElementById('sel');
sel.options[sel.selectedIndex].text; // 畫面上顯示的文字
sel.options[sel.selectedIndex].value; // 送到後端的值
selectedIndex 告訴你是第幾個選項被選中,再用它去索引 options 集合,就能同時拿到 text 與 value。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>取得 select 選中項</title>
<script type="text/javascript">
function selChange(){
var sel = document.getElementById('sel');
alert(sel.options[sel.selectedIndex].text); // 例如「張三」
alert(sel.options[sel.selectedIndex].value); // 例如「zhangsan」
}
</script>
</head>
<body>
<select id="sel" onchange="selChange()">
<option value="zhangsan">張三</option>
<option value="lisi">李四</option>
<option value="wangwu">王五</option>
</select>
</body>
</html>
選擇不同項目時,會依序跳出對應的文字與值。
幾個容易忽略的細節值得留意:
預設值——若沒有任何 option 標上 selected,瀏覽器會預設選中第一項,因此 selectedIndex 通常不會是 -1;只有在表單尚未初始化或被程式刻意取消選取時才會出現 -1,取值前仍建議防呆。
取值時機——請確認要讀取的 select 已經存在於 DOM 中,否則 getElementById 會回傳 null。
大量選項——若一次要收集全部選項,改用迴圈搭配 sel.options[i] 即可,不必依賴 selectedIndex。