开发者

selectedIndex is returning "undefined" as value

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:

&l开发者_运维技巧t;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>


A <select>'s selectedIndex property 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).

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;


Try this:

f.prefix.value = f.editprefixes.options[f.editprefixes.selectedIndex].value;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜