獲取select被選中option的value和text
阿新 • • 發佈:2019-02-01
要獲取select選中的value,或者text
比如這個:
<select id="select">
<option value="A" url="http://www.baidu.com">第一個option</option>
<option value="B" url="http://www.qq.com">第二個option</option>
</select>
一:JavaScript原生的方法
1:拿到select物件:
var myselect=document.getElementById("select" );
2:拿到選中項的索引:
var index=myselect.selectedIndex ; // selectedIndex代表的是你所選中項的index
3:拿到選中項options的value:
myselect.options[index].value;
4:拿到選中項options的text:
myselect.options[index].text;
5:拿到選中項的其他值,比如這裡的url:
myselect.options[index].getAttribute('url');
二:jQuery方法
1.var options=$( “#select option:selected”); //獲取選中的項
2.alert(options.val()); //拿到選中項的值
3.alert(options.text()); //拿到選中項的文字
4.alert(options.attr('url')); //拿到選中項的url值