使用 jQuery 通过组合框的名称获取组合框的选定文本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8850088/
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
Get selected text of a combo box using jQuery, by name of the combo box?
提问by Tech Care
How Can I get selected text value from the combo box using jQuery.
如何使用 jQuery 从组合框中获取选定的文本值。
I am having only "name" of combo box.
我只有组合框的“名称”。
So, I want the text of selected item, using the nameof combo box, not ID.
所以,我想要所选项目的文本,使用组合框的名称,而不是 ID。
I am having ,
我有,
var selected_fld = ( $(this).attr('name') );
How can I proceed further ?
我怎样才能进一步?
回答by Constantin Gro?
$('select[name=nameOfTheBox]').val();
or
或者
$('select[name=nameOfTheBox] option:selected').val();
will give you the value of the selected option
将为您提供所选选项的值
$('select[name=nameOfTheBox] option:selected').text();
will give you its text
会给你它的文字
回答by musefan
This can be done simply with the following to get the actual text value...
这可以通过以下简单地完成以获得实际的文本值......
var value = $("[name='MyName'] option:selected").text();
or this to get the option 'value' attribute...
或者这是为了获得选项“值”属性......
var value = $("[name='MyName']").val();
With the following html, the first will give you 'MyText', the second will give you 'MyValue'
使用以下 html,第一个会给你“MyText”,第二个会给你“MyValue”
<select name="MyName">
<option value="MyValue" selected="selected">MyText</option>
</select>
回答by Hemant Metalia
try following
尝试跟随
<select name="name1">
<option value="val1">val1</option>
<option value = "val2">val2</option>
</select>
var text = $("select[name='name1'] option:selected").text();
回答by Megha
<select id ="myCombo">
<option value="Play selected="selected">Here</option>
<option value="Once">Again</option>
</select>
$('#myCombo option:selected').text();
This will return you "here"
这将使您返回“此处”
$('myCombo option:selected').val();
This will return you "Play"
这将返回您“播放”
回答by Bhanu Pratap
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="jquery-3.1.0.js"></script>
<script>
$(function () {
$('#selectnumber').change(function(){
alert('.val() = ' + $('#selectnumber').val() + ' AND html() = ' + $('#selectnumber option:selected').html() + ' AND .text() = ' + $('#selectnumber option:selected').text());
})
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<select id="selectnumber">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
<option value="4">four</option>
</select>
</div>
</form>
</body>
</html>
Thanks... :)
谢谢... :)