|
|
|
The following example is going to show you how to check the selected index of a select object and then redirect the user to the option they selected as soon as they select it. The options in the select are:
Open the form and give it a name
<form name="myForm">
<select name="myUrlList">
Register the onChange event
<select name="myUrlList"
onchange="">
Make the onChange event call the setLocation function
<select name="myUrlList"
onchange="setLocation()">
<option selected>Choose one
Define the other options and set their value to a valid web site address without the "http://" protocol and provide an explanation for the value beside the option.
<option value="java.sun.com">Sun's Java
<option value="Apache.org">Apache
<option value="CoolText.com">CoolText
<option value="JShortcut.com">JavaScript Shortcuts
</select>
</form>
This function first declares three local variables protocol, listReference and selectedIndex. The protocol is assigned the "http://" value (All these web sites use this protocol) straight away which will be inserted at the beginning of the chosen web site as the protocol. ListReference is used as a reference to the select object. SelectedIndex is set to the selected index of the listReference pointer.
After the local variables are set the function then checks if the selected index is "0" if it is it means the user chose the first option in the select which does not provide a valid URL so the function doesn't do anything. Otherwise the selected index must be between "1" and "3" which means the user choices a valid web address. If this is the case it declares another local variable "optionValue" which is assigned the value of the selected option. It does this by accesing listReference's option array. (This array contains all options of the select and is named options) and getting the option out of the option array at the index the user chose using selectedIndex.
Finally the window's location property is set to the protocol variable with the web site address attached to the end of the string. The window's location then changes to the chosen web address.
function setLocation(){
var protocol = "http://";
Get a reference to the select
var listReference = document.myForm.myUrlList
Get the selected index
var selectedIndex = listReference.selectedIndex
If the selected index is not the first option in the select
if(selectedIndex != 0){
var optionValue
Get the value from the select by using the listReference and accessing it's options array and getting the option of the array the user chose.
optionValue = listReference.options[selectedIndex].value
Change the location of the window to the web adress using the "http://" protocol
window.location = protocol + optionValue
}
}
If the sleectedIndex property is -1 it means nothing is selected
See also Checkbox | Radio button | Querying a text field's value