處理表單時,絕大多數情況我們關心的是 <option> 的 value,因為那才是要送到後端的資料。但有時候使用者看到的、我們需要的卻是畫面上那段文字,例如一個城市下拉選單,value 是 1、2,而顯示的是「北京」「上海」。
關鍵在於 select.options[select.selectedIndex] 這個組合:它指向使用者目前選中的那個 option 節點,而 option 節點上同時有 value 屬性和文字內容。
<script type="text/javascript">
function a(object){
alert(object);
}
</script>
<!-- 取得畫面上顯示的文字 -->
<select onchange="a(this.options[this.selectedIndex].innerText);">
<option value="value-a">text-a</option>
<option value="value-b">text-b</option>
</select>
<!-- 取得 value 值 -->
<select onchange="a(this.options[this.selectedIndex].value);">
<option value="value-c">text-c</option>
<option value="value-d">text-d</option>
</select>
這裡有個跨瀏覽器的小地雷:innerText 在舊 Firefox 不支援,實務上建議改用 textContent,或寫成 el.innerText || el.textContent 做相容處理。
把這個技巧放進真實場景,最常見的就是「請先選擇再送出」的驗證。當 value 為預設的 -1 時,代表使用者還沒挑選,此時阻止提交並提示;否則允許表單送出。
function isSelect(selectPress) {
// 畫面上顯示的文字,例如「北京」「上海」
var selectValue = selectPress.options[selectPress.selectedIndex].value;
var selectValue2 = selectPress.options[selectPress.selectedIndex].innerText;
if (selectValue == "-1") {
alert("請選擇城市,表單提交被拒絕!");
return false;
} else {
document.getElementById('form1').submit();
return true;
}
}
</script>
<select onchange="isSelect(this);" id="mySelect">
<option value="-1">--請選擇--</option>
<option value="0">北京</option>
<option value="1">上海</option>
<option value="2">武漢</option>
</select>
記住這條對應關係就不會混淆:selectedIndex 是索引、options[n].value 是值、options[n].text 是文字。三者分工清楚之後,下拉選單的讀取與驗證都只是排列組合而已。