javascript 如何从选择元素中获取所选选项的文本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5676030/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get text of a selected option from the select element?
提问by Richard Knop
EDIT: The HTML and js bellow is a simplified version. Check out the jsfiddle link on the bottom of my post for full demonstration of my problem.
编辑:下面的 HTML 和 js 是一个简化版本。查看我帖子底部的 jsfiddle 链接以完整演示我的问题。
I have a select HTML element:
我有一个选择的 HTML 元素:
<select name="foo" id="foo">
<option value="1">a</option>
<option value="2">b</option>
<option value="3">c</option>
</select>
I want to get the label of a selected option with jQuery. This, however:
我想使用 jQuery 获取所选选项的标签。然而,这:
alert($("#foo option:selected").text());
Returns:
返回:
a
b
c
I want to get just, for example:
我想得到,例如:
b
jsfiddle: http://jsfiddle.net/8KcYY/1/(click on the "Vybra? zna?ku" button).
jsfiddle:http: //jsfiddle.net/8KcYY/1/(点击“Vybra?zna?ku”按钮)。
回答by Kon
This works:
这有效:
<select name="foo" id="foo">
<option value="1">a</option>
<option value="2">b</option>
<option value="3">c</option>
</select>
<input type="button" id="button" value="Button" />
$('#button').click(function() {
alert($('#foo option:selected').text());
});
Try it yourself: http://jsfiddle.net/Nyenh/
自己试试:http: //jsfiddle.net/Nyenh/
Even simpler:
更简单:
$('#foo').change(function(){
var selected = $(this).find('option:selected');
alert(selected.val() + ' ' + selected.text());
});
回答by Anand Thangappan
$("#dropdownlistID").text();
This will show all positions in your "dropdownlist". To get only selected item use:
这将显示“下拉列表”中的所有位置。要仅获取选定的项目,请使用:
$("#dropdownlistID").val();
Or try like
或者尝试像
$("#foo").find(":selected").text()
instead of
代替
$("#foo option:selected").text()