Previous Example-|-Next Example-|-Return to Chapter Listing

Example 17.9:
Getting Text from Select Boxes

You can get the text of the selected item by clicking the button. This script gets the index position of the option in the select box, then uses the options array to find the actual text held in that index position.
Pick an option from the Select box:


We've used this system in our Color Chart. There's also another way to do this, if you are writing scripts for Netscape Navigator 3; see Example 17.11.
These are the scripts we used. First, in the HEAD: <SCRIPT LANGUAGE="JAVASCRIPT"> <!-- function DisplayItem(Myform) { var i = Myform.lstOption.selectedIndex var sText = Myform.lstOption.options[i].text alert(sText) } //--> </SCRIPT> Later in the Web page the function is called from this form: <FORM> Pick an option from the Select box: <BR> <SELECT name="lstOption"> <OPTION>Text at Index=0 <OPTION>Text at Index=1 <OPTION>Text at Index=2 <OPTION>Text at Index=3 <OPTION>Text at Index=4 <OPTION>And here's more... </SELECT> <BR> <INPUT TYPE="button" VALUE="Click to display the text from the selected option" onclick="DisplayItem(this.form)"> </FORM>
Previous Example-|-Next Example-|-Return to Chapter Listing