获取select选中的值

获取到select下面的所有值或者当前选中的值:

html:

<select id="select">
    <option value="A" url="http://www.baidu.com">默认</option>
    <option value="B" url="http://www.qq.com">第一个选择</option>
   <option value="C" url="http://www.163.com">第二个选择</option>
</select>

原生方法:

1:拿到select对象: `var select=document.getElementById("select");

2:拿到选中项的索引:var index=select.selectedIndex ; // selectedIndex代表的是你所选中项的index

3:拿到选中项options的value: select.options[index].value;

4:拿到选中项options的text: select.options[index].text;

5:拿到选中项的其他值,比如这里的url: select.options[index].getAttribute('url');

jQuery方法:

1:var options=$(“#select option:selected”); //获取选中的项

2:console.log(options.val()); //拿到选中项的值

3:console.log(options.text()); //拿到选中项的文本

4:console.log(options.attr('url')); //拿到选中项的url值

jQuery获取select下的option索引的多种方法:

var w = $('select').prop('selectedIndex');
var s = $('select option:selected').index();
var a = $('select option').index($('select option:selected'))

三种方式均可获取到select下面的option的索引值

 

完整例子:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <select name="" id="select">
        <option value="" id="ddd">请选择</option>
        <option value="A" url="http://www.baidu.com">默认</option>
        <option value="B" url="http://www.qq.com">第一个选择</option>
       <option value="C" url="http://www.163.com">第二个选择</option>
    </select>
</body>
</html>
<script src="jquery-1.11.1.js"></script>
<script>
$('select').on('change',function(){
    var options = $('select option:selected');
    var index1 = $('select').prop('selectedIndex');//获取option索引值
    var index2 = options.index();//获取option索引值
    var index3 = $('select option').index(options);//获取option索引值

    var txt = options.text();//获取当前选中项的文本内容
    var val = options.val();//获取当前选中项的value值

    var attrOpt = options.attr('url');//获取当前选中项的属性url
    
})

</script>

 

转载于:https://www.cnblogs.com/moutudou/p/8365550.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值