開發中我們最常取用的是 option 的 value,但有時也需要拿到顯示在頁面上的文字,例如想獲得 <option value="value">ShowText</option> 裡的 "ShowText"。方法其實很簡單:透過 selectedIndex 定位選中項,再用 .value 取數值、用 .innerText(或 .text)取顯示文字。
代碼如下:
<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>
如果把取值封裝成函數,還能順帶做表單校驗,例如判斷用戶是否已選擇:
function isSelect(selectPress) {
var selectValue = selectPress.options[selectPress.selectedIndex].value; //顯示 value
var selectValue2 = selectPress.options[selectPress.selectedIndex].innerText; //顯示文字內容
if (selectValue == "-1") {
alert("請選擇城市,表單提交被拒絕!")
return;
} else {
document.getElementById('form1').submit(); //提交表單
}
}
<select onchange="isSelect(this);" id="mySelect">
<option value="-1">--請選擇--</option>
<option value="0">北京</option>
<option value="1">上海</option>
<option value="2">武漢</option>
</select>
小結:this.options[this.selectedIndex].value 取的是數值,.innerText 取的是頁面上的顯示文字;搭配一個佔位選項(value 為 -1)並在提交前做判斷,就能避免用戶忘記選擇。需要注意的是 innerText 並非跨瀏覽器標準,如需更佳兼容性可改用 .text 屬性。