Select Boxes
Select boxes are great because they can hold a large number of options in a very small screen space. Check out this example. It takes up only a small line until it's needed (clicked). Then it drops down to display any number of options.
This lesson will show you how to use JavaScript to detect and use the viewer's selected option. Begin by making a select box. If you need a review, go here.
Here's the code that made the select box in the example:
<form name="navform">
<select name="navbox">
<option>-- Select A Search Engine --
<option>
<option value="http://www.google.com/">Google
<option value="http://www.yahoo.com/">Yahoo!
<option value="http://www.altavista.com/">Alta Vista
<option value="http://www.about.com/">About.com
</select>
<input type="button" value="Go!" onClick="gothere()">
</form>
You'll note that the <option>s are very different from radio buttons and checkboxes. They need no name. They are grouped by being placed in between a NAMEd <select> tag. They consist of two major parts -- 1) the VALUE and, 2) the text label that appears in the box.
The collection of <option>s in a <select> form an array. We would refer to the value of the "Google" option ("http://www.google.com/") in our select box like this:
document.navform.navbox.options[2].value;
The above points to the third <option> tag coded. The one for Google. Note that there are two <option> tags before the Google one. Each <option> counts even if it has no VALUE attribute or text tag.
Now for some good news. Unlike radio buttons and checkboxes, you don't need to loop through the options to find the selected one. There's a property that does that for us.
selectedIndex
The "selectedIndex" property will return the array number of the <option> selected. There's some confusion about this and how to use it. The term "selectedIndex" alone doesn't return a value. It must be used in a full reference to the particular <select> set of options:
document.navform.navbox.options.selectedIndex
The above would return the number corresponding to the option selected. If we had selected the Google <option>, the "document.navform.options.selectedIndex" would be 2. Don't forget to capitalize the "I" in the "Index" part of "selectedIndex".
We can put this "selectedIndex" number in the square brackets of:
document.navform.navbox.options[array_number].value
This would give us the VALUE of the viewer's selected <option>. Here's what the whole thing looks like:
document.navform.navbox.options
[document.navform.navbox.options.selectedIndex].value
Wow, that's a mouthful. One mistake that is common is to try to use:
document.navform.navbox.options[selectedIndex].value;
The above just doesn't work. The "selectedIndex" property cannot stand alone. No property can. It must be associated with an object, so the entire object reference must be used when the "selectedIndex" number is needed.
What the above does is return the value for "document.navform.navbox.options.selectedIndex" and then errors when there is no "value" property to the "selectedIndex" property. "selectedIndex" is a property and has no sub-properties like "value".
There is, thank goodness, a shortcut that can save such a long object reference. We can assign the parent object -- "document.navform.navbox.options" -- to a variable and then use the variable instead of the object.
var box = document.navform.navbox.options;
var chosen_value = box[box.selectedIndex].value;
The above technique not only cuts down on typing (and typos), but makes the code easier to read and debug as well. Many coders use an alternative and put the "selectedIndex" value in a variable:
var choice = document.navform.navbox.options.selectedIndex;
document.navform.navbox.options[choice].value;
You can use whichever method suits you best. It's a good idea, though, to use a variable to hold parent object(s) or the "selectedIndex" value so as to cut down on typing and overall bulk in your code.
Now that we can get the VALUE from an option, we need to assign it to a variable for use by the rest of the script. In the example I used "where_to" for this variable:
function gothere(){
var box = document.navform.navbox.options;
var where_to = box[box.selectedIndex].value;
...
The "where_to" variable now contains the value of the viewer's selection and can be used elsewhere in the script. In our example, the VALUE is a URL and we use it to change the "window.location" property.
Error Control
The select box used in our example uses some <option> tags for a little stying. The first <option> makes a title and the second makes a line break between the title and "Google". What would happen if one of these were selected and sent to the JavaScript?
In our case, it would cause an error. The "window.location" property won't take an empty string. We need some way to detect if one of the "value-less" options was selected and handle it outside of our "window.location" line.
We can detect the error with an IF statement. The problem is that there is no VALUE. The following will detect the absence of a VALUE:
if (where_to == ""){return}
else {window.location = where_to;}
All we are doing is checking to see if "where_to" (which holds the <option>'s VALUE) is an empty string. If it is, I used the return statement. The return statement will stop a JavaScript from running once it is encountered. It "returns" the veiwer back to the regular page and quits processing the JavaScript.
The "return" statement is heavily used in error control. Whenever an error is detected with an IF statement, a return can be run to stop the JavaScript from continuing. Often an alert box explaining the error is run first.
Alternatively, the more elegant error detection would go:
if (where_to != "") {window.location = where_to}
In the code above, we don't use an ELSE and that causes the script to do nothing when "where_to" is empty.The above is preferable, but I wanted to introduce the empty brackets technique. Keep it in mind if you ever have an option in a series if IF/ELSEs where you want absolutely nothing done.
onChange Technique
You don't have to use a submit button when using select boxes. You can use the "onChange" event as in this example. You just click the option and the JavaScript runs immediately.
This is really simple. Just delete the submit button code and the ACTION attribute in the <form> tag. Now just add an "onChange" event to the <select> tag:
<select name="navbox" onChange="gothere()">
The above would lead to the the "gothere()" function we've already coded. Just a different event calling it.
There are a couple of problems with using the "onChange" event. First, the viewer doesn't have a second chance to make a selection as he does with the submit button. This can irritate some folks. On the other hand, it saves a click and is more "mouse efficient".
Another problem occurs when someone leaves your page, comes back, and their old choice is still selected. What if they want to pick that same option again? There will be no "change" for the "onChange" event and nothing will happen.
To get around this we can reset our <form> automatically. This will always select the first <option> by default. If that option is an "empty" one, like a title or blank space, they can reselect their previous option as well as any other active option with a VALUE.
To reset the form, use the "onLoad" event in the <body> tag:
<body onLoad="document.navform.reset()">
We'll be talking about the "reset()" method more later. For now remember that it applies to whole forms, not individual boxes and form elements.
Summary & Exercises
Select box <option>s form an array that can be accessed with Javascript. The VALUE attribute of these <option>s can be read and used. The object reference for these VALUEs is:
"document.form_name.select_name.options[array_number].value".
To find the array number of the viewer's selected option, we can use the "selectedIndex" property of the option's array:
"document.form_name.select_name.options.selectedIndex".
Using both the reference for an option's value and "selectedIndex", we can get the value of whatever option a viewer selects. In full, this is a really long line of code:
"document.form_name.select_name.options[
document.form_name.select_name.options. selectedIndex].value". (Note that I added some line breaks and spaces in the sample code to keep the page from being too wide to view. These are not present in the actual, working code. There are no spaces in object references.)
To spare ourselves such long object references, we can assign a variable to a parent object or the "selectedIndex" property. Using a variable for the parent object is a common technique when dealing with long object references:
"var block = document.form_name.select_name.options;". Now we can just use the variable "block" instead of the full reference to the parent object (the options array).
You can use select boxes for a variety of things, but using them for navigating a large number of links is very useful. This is because you can store a hundred links in a visually small box. It only expands when the viewer wants it to. It only takes 5 steps:
1) Make the form and box using appropriate VALUEs.
2) Pick a JavaScript event and code a function call. Submit buttons and "onChange" are common for select boxes.
3) Start coding the function by assigning a variable to parent objects, like the option array -- "document.form_name.select_name.options".
4) Get the "value" property from the selected option. Assign it to a variable.
5) Use the variable holding the VALUE of the selection as needed.
Make a page with a form containing more than one select box. Use one to color the page's background, another to go to another page, etc.
To Next Advanced JavaScript Lesson
Back To Advanced JavaScript Index
|