1. 程式人生 > >Js獲取select value值、索引 onchange事件觸發

Js獲取select value值、索引 onchange事件觸發

			<div class="num">
			<select id="xuanze" onchange="changeValue();">
				<option value="10">10</option>
				<option value="15">15</option>
				<option value="20">20</option>
				<option value="25">25</option>
				<option value="30">30</option>
				<option value="35">35</option>
				<option value="40">40</option>
			</select>
			</div>
<script type="text/javascript">
function changeValue(){
    	var obj = document.getElementById('xuanze'); //定位id
		var index = obj.selectedIndex; // 選中索引
		var value = obj.options[index].value; // 選中值
  }
        var n1 = Number(value);
</script>

現在有一id=test的下拉框,怎麼拿到選中的那個值呢?

分別使用javascript原生的方法和jquery方法

<select id="test"  name="">   
  <option   value="1">text1</option>   
  <option   value="2">text2</option>   
 </select>

code:

一:javascript原生的方法

  1:拿到select物件: var  myselect=document.getElementById("test");

  2:拿到選中項的索引:var index=myselect.selectedIndex ;             // selectedIndex代表的是你所選中項的index

  3:拿到選中項options的value:  myselect.options[index].value;

  4:拿到選中項options的text:  myselect.options[index].text;

二:jquery方法(前提是已經載入了jquery庫)

1:var options=$("#test option:selected");  //獲取選中的項

2:alert(options.val());   //拿到選中項的值

3:alert(options.text());   //拿到選中項的文字