JS、JQUERY获取select被选中option的value和text的值

做网站时,在select选择框中,往往需要获取select被选中option的value和text的值,并且传给其它位置使用。获取select被选中option的value和text的值,一般需要使用JS或者JQUERY代码来获取。

JS、JQUERY获取select被选中option的value和text的值


<select id="select">
<option value="学做网站论坛" url="http://ke.xuewangzhan.net/">学做网站论坛</option>
<option value="WP模板阁" url="https://aiwangxue.com/">WP模板阁</option>
</select>

JS获取select被选中option的value和text的值

  • 1:拿到select对象:
    
    
    var myselect=document.getElementById("select");
  • 2:拿到选中项的索引:
    
    
    var index=myselect.selectedIndex;

    // selectedIndex代表的是你所选中项的index

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

    或者直接使用:

    
    
    myselect.options[myselect.selectedIndex].value;
  • 4:拿到选中项options的text:
    
    
    myselect.options[index].text;

    或者直接使用:

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

    或者直接使用:

    
    
    myselect.options[myselect.selectedIndex].getAttribute('url');

JQUERY获取select被选中option的value和text的值

1:获取选中的项


var options=$(“#select option:selected”);

2:拿到选中项的值


alert(options.val());

3:拿到选中项的文本


alert(options.text());

4:拿到选中项的url值


alert(options.attr('url'));
关闭 维课网微信