Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

selectedIndex is returning "undefined" as value

Tags:

javascript

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:

<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>
like image 609
EmmyS Avatar asked Aug 25 '10 16:08

EmmyS


1 Answers

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;
like image 177
Daniel Vandersluis Avatar answered Sep 21 '22 01:09

Daniel Vandersluis