js動態獲取select選中的option


 最近在寫報表管理模塊時,需要通過條件去篩選符合條件的數據,篩選條件用的布局有select,input等。在調試的過程中一直獲取不到select選中的option。於是就查詢些資料,發現用select的selected屬性可以獲取到option的值。下面通過demo來演示:

通過2種方式:

一、jquery方法(頁面中必須加載過jquery庫)-------------------推薦使用

1:var options=$("#test option:selected");  //獲取選中的項
2:alert(options.val());   //拿到選中項的值
3:alert(options.text());   //拿到選中項的文本

demo代碼:

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

二、通過原生js方法

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;

 

推薦使用第一種jqueiry方法去獲取select選中的option~~~~~~~~


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM