zoukankan      html  css  js  c++  java
  • 获取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>
  • 相关阅读:
    poj3481
    查找湖南问题
    tyvj1033
    tyvj1088
    oil倒油
    加分二叉树
    模拟题2
    模拟题3
    Free pascal中的random函数
    Spring MVC入门配置
  • 原文地址:https://www.cnblogs.com/moutudou/p/8365550.html
Copyright © 2011-2022 走看看