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~~~~~~~~

发布了80 篇原创文章 · 获赞 4 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/tscaxx/article/details/104229983