Javascript: Select box navigation
November 29th, 2006 at 10:50 am (Garbage Tip)
So, you have this form object such as the one illustrated below.
<form>
<select class="button" size="1" id="idname">
<option>Section I </option>
<option>Section II </option>
<option>Section III </option>
<option>Section IV </option>
<option>Section V </option>
<option>Section VI </option>
<option>Home </option>
</select>
<input type="button" class="button"
onclick="selectOption('idname', URLarray)" value="Go" />
</form>
You could attach a routine written specifically for that object. Or you could initialize an array with the values for each option and call a routine that knows how to handle such an array passed to it. Here is an example of such a function named selectObject():
//generic list item function
function selectOption(ident, listItemURL)
{
var selObj = document.getElementById(ident);
var num = selObj.selectedIndex;
for (i=0; i<listItemURL.length; i++) {
if (i==num) {
top.location= baseURL + listItemURL[i];
break;
}
}
}
Somewhere before that function you’ll need to initialize an array to pass as a listItemURL parameter. Here’s an example:
var somearray1 = new Array( '/directory/somefile1.shtml', '/directory/somefile2.shtml', '/directory/somefile3.shtml', '/directory/somefile4.shtml', '/directory/somefile5.shtml', '/directory/somefile6.shtml', '/index.shtml' );
The form parameter URLarray in this case would be somearray1.
In the function, the optional variable baseURL is also initialized elsewhere, depending on the structure of the files. It is not required in this example as the values of the array in this case are based in the root directory by default. You might, however, want a base url, in which case you would declare it in a header page that would include the head portion of your shtml document. One way to do that would be as follows:
<script>
//Base URL variable is used in .js file as well
var urlhost = location.host;
var locpath = location.pathname;
var pathtohome = locpath.substr(0, locpath.indexOf('/somedirectory'));
var baseURL = "http://" + urlhost + pathtohome + "/somedirectory/";
document.write('<base href="' + baseURL + '"></base>');
</script>
This declaration would be placed before the function.
The long and short of it is you need only call one function to make a particular select box object work once you have declared an array of option values and successfully passed that array to the function.



