We can use javascript to find which item is selected from a drop box. Try it.
This is the most complicated form control to retrieve values from.
This is due to the fact that items in a select box represent an array of options
We will use the DOM method and assume we are refering to the first select box in the first form on a page.
This code gets you the text of a selected item from the above drop box.
document.forms[0].elements[0].options[document.forms[0].elements[0].selectedIndex].text
It looks complicated but it is really a question of following the DOM and using the selectedIndex property of the select box.
The Dom treats the items in a select box as a set of options.
The section [document.forms[0].elements[0].selectedIndex] gets you the numeric index of a particular option in the select box.
Lets look at an example
Selecting Orac generates an onChange event with a selectedIndex value of 2
Therefore name=document.forms[0].elements[0].options[document.forms[0].elements[0].selectedIndex].text
becomes name=document.forms[0].elements[0].options[2].text ;
We can display the name of the selected option with window.alert(name);
Exercise
Create a web page using the code below.
Add two more options to the list.
<head><script type='text/javascript'>
function picked(){
name= document.forms[0].elements[0].options[document.forms[0].elements[0].selectedIndex].text;
window.alert(name);
}
</script></head>
<body><form>
<select onchange=picked();>
<option>Mike</option>
<option>Mary</option>
<option>Fred</option>
</select></form>
</body>
Here is an example of populating a drop box with items selected from another drop box.
Check out
Shop till you Drop then view the source code.