使用 JavaScript 获取选项文本/值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4641962/
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
Getting an option text/value with JavaScript
提问by Phil
Answer: var option_user_selection = element.options[element.selectedIndex].text
回答:var option_user_selection = element.options[element.selectedIndex].text
I am trying to build a form that fills in a person's order.
我正在尝试构建一个填写个人订单的表格。
<form name="food_select">
<select name="maincourse" onchange="firstStep(this)">
<option>- select -</option>
<option text="breakfast">breakfast</option>
<option text="lunch">lunch</option>
<option text="dinner">dinner</option>
</select>
</form>
What I'm trying to do is send in the select object, pull the name and the text/value from the option menu AND the data in the option tag.
我想要做的是发送选择对象,从选项菜单中提取名称和文本/值以及选项标签中的数据。
function firstStep(element) {
//Grab information from input element object
/and place them in local variables
var select_name = element.name;
var option_value = element.value;
}
I can get the name and the option value, but I can't seem to get the text="" or the value="" from the select object. I only need the text/value from the option menu the user selected. I know I can place them in an array, but that doesn't help
我可以获取名称和选项值,但似乎无法从选择对象中获取 text="" 或 value=""。我只需要用户选择的选项菜单中的文本/值。我知道我可以将它们放在一个数组中,但这无济于事
var option_user_selection = element.options[ whatever they select ].text
I also need to use the passed in select reference as that is how it's set up in the rest of my code.
我还需要使用传入的 select 引用,因为它是在我的其余代码中设置的。
Later on, that text/value is going to be used to pull the XML document that will populate the next select form dynamically.
稍后,该文本/值将用于提取将动态填充下一个选择表单的 XML 文档。
回答by Chandu
You can use:
您可以使用:
var option_user_selection = element.options[ element.selectedIndex ].text
回答by Morganster
In jquery you could try this $("#select_id>option:selected").text()
在 jquery 你可以试试这个 $("#select_id>option:selected").text()
回答by M99
form.MySelect.options[form.MySelect.selectedIndex].value
回答by Kreeverp
var option_user_selection = document.getElementById("maincourse").options[document.getElementById("maincourse").selectedIndex ].text