Javascript selectedIndex 返回“未定义”作为值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3568171/
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
selectedIndex is returning "undefined" as value
提问by EmmyS
Forgive me if this is a stupid question; it's been many years since I've worked with javascript. This is actually javascript and html rendered via PHP in Joomla, but I've tried using the same code in a plain old local HTML file and I'm getting the same error. I have a select field with several options, and onchange I want to set the value of a text field to the value of the selected option. No matter which option I choose, the text field is being set to "undefined". Can anyone help me out? Here's the plain html code:
如果这是一个愚蠢的问题,请原谅我;自从我使用 javascript 以来已经很多年了。这实际上是在 Joomla 中通过 PHP 呈现的 javascript 和 html,但我尝试在一个普通的旧本地 HTML 文件中使用相同的代码,但我遇到了同样的错误。我有一个带有多个选项的选择字段,并且 onchange 我想将文本字段的值设置为所选选项的值。无论我选择哪个选项,文本字段都被设置为“未定义”。谁能帮我吗?这是纯html代码:
<html>
<head>
<script type="text/javascript">
function setPrefix(){
var f = document.adminForm;
f.prefix.value = f.editprefixes.selectedIndex.value;
}
</script>
</head>
<body>
<form name="adminForm">
<select name="editprefixes" onchange="javascript:setPrefix()">
<option value=1000>1000</option>
<option value=1001>1001</option>
<option value=1005>1005</option>
<option value=1011>1011</option>
<option value=1016>1016</option>
</select>
<br />
<input type="text" name="prefix" value="" />
</form>
</body>
</html>
采纳答案by Daniel Vandersluis
A <select>'s selectedIndexproperty does not refer to an actual <option>object, but rather is an integer corresponding to the index of the option that is selected (so the first option is 0, second is 1, and so on).
A<select>的selectedIndex属性不是指实际<option>对象,而是与所选选项的索引相对应的整数(因此第一个选项为 0,第二个为 1,依此类推)。
If you want to get the value of the selected option, you need to use:
如果要获取所选选项的值,则需要使用:
var sel = f.editprefixes;
f.prefix.value = sel.options[sel.selectedIndex].value;
回答by theycallmemorty
Try this:
尝试这个:
f.prefix.value = f.editprefixes.options[f.editprefixes.selectedIndex].value;

