2000字范文,分享全网优秀范文,学习好帮手!
2000字范文 > Javascript和jquery获取select下拉框选中的的值和文本

Javascript和jquery获取select下拉框选中的的值和文本

时间:2018-11-26 17:48:16

相关推荐

Javascript和jquery获取select下拉框选中的的值和文本

PS:JS里面只能用getElementById()来获取下拉列表框的值。****

现在有一id=test的下拉框,怎么拿到选中的那个值呢?

分别使用javascript原生的方法和jquery方法

<select id="test" name="">

<option value="1">text1</option>

<option value="2">text2</option>

</select>

code:

一:javascript原生的方法

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;

二 jquery

/*获取下拉列表框的值和文本,jquery没有选择name的*/

$('#mysub').click(function(){

alert($('select option:selected').val());

alert($('select option:selected').text());

})

jQuery 属性选择器

jQuery 使用 XPath 表达式来选择带有给定属性的元素。

$("[href]") 选取所有带有 href 属性的元素。

$("[href='#']") 选取所有带有 href 值等于 "#" 的元素。

$("[href!='#']") 选取所有带有 href 值不等于 "#" 的元素。

$("[href$='.jpg']") 选取所有 href 值以 ".jpg" 结尾的元素。

$("[name='sub']").click(function(){//单引号和双引号'[name="sub"]' 这样写也对

alert($('select option:selected').val());

alert($('select option:selected').text());

})

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。