javascript如何獲取當前選中的option項的文字和value值

antzone發表於2017-03-17

select下拉選單是最為常用的表單元素之一,下面介紹一下如何獲取select下拉選單當前被選中option項的文字值和value值。

程式碼如下:

[HTML] 純文字檢視 複製程式碼
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<script type="text/javascript">
function check() {
  var sel=document.getElementById("sel");
  var selValue=sel.options[sel.options.selectedIndex].value;
  var selTxt=sel.options[sel.options.selectedIndex].text;
  alert(selValue);
  alert(selTxt);
}
window.onload=function(){
  var bt=document.getElementById("bt");
  bt.onclick=function(){
    check() 
  }
}
</script>
</head>
<body>
<select name="select" id="sel">
  <option value="1" selected="selected">螞蟻部落一</option>
  <option value="2">螞蟻部落二</option>
</select>
<input type="button" value="點選獲取" id="bt"/>
</div>
</body>
</html>

以上程式碼能夠彈出被選項的value值和text文字值,下面做一下簡單介紹:

1.var sel=document.getElementById("sel"),獲取select物件

2.sel.options.selectedIndex,獲取被選中項的索引值。

3.sel.options[sel.options.selectedIndex].value,獲取被選中項值,sel.options獲取option項的物件集合,根據索引值訪問相關項,使用value是獲取的value屬性值,使用text獲取的是文字值。

更多相關內容可以參閱javascript動態操作select下拉選單一章節。

相關文章