tags:

views:

28

answers:

3

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>
+3  A: 

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;
Daniel Vandersluis
+1, a good explanation. FWIW, `sel.value` would also work for this scenario in all browsers.
Andy E
Thanks, that worked. It's coming back to me now...
EmmyS
+1  A: 

Try this:

f.prefix.value = f.editprefixes.options[f.editprefixes.selectedIndex].value;
theycallmemorty
+1  A: 

You should use jQuery!

palswim
Actually, please don't.
palswim
jQuery is kind of like swatting a fly with a Cadillac for something this simple...
EmmyS
@EmmyS: Oh good, you're the question asker and you realize that you shouldn't use jQuery. I was hoping you didn't take my advice. ^_-
palswim