Javascript獲取select下拉框選中的的值

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

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

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

一: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());   //拿到選中項的文本


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章