Journal

Jumping Java Jive

PC Pro logo Posted: 1st May 1999 | Filed under: Press Articles, Technical
Author: Paul Ockenden
First Appeared in PC Pro 1999

Reader David Netter writes: 'I use a dropdown list for site navigation, but at the moment it requires the user to select a page and then press a Go! button. I've seen sites which do the page jump automatically when the selection is done. How can I do this on my site?'

The answer is JavaScript. You'll find a number of solutions to this problem in the various free script archives, but here's the code we use:


<SCRIPT LANGUAGE="JavaScript">
<!--
function findObj(frm, nme)
{

var obj;
for(i=0; i < frm.elements.length; i++)
{

if(frm.elements[i].name == nme)
{

obj = frm.elements[i];

}

}
return obj;

}
function goToUrl(x)
{

var frm = this.document.forms[0];
var obj = findObj(frm,x);
var url = obj.options[obj.selectedIndex]. value;
if (url != "")
{

self.location.href = obj.options[obj.selectedIndex]. value;

}
return true;

}
// -->
</SCRIPT>

Our code is more flexible than many of the examples you'll find, because it can cope with multiple selection boxes. For example, you might have something like the following for features, news and off-site links:


<form action="redirect.pl" method="POST">

<SELECT NAME="select1" onChange="goToUrl('select1')">
<OPTION SELECTED VALUE="">Special Features</OPTION>
<option value="features/this.asp">Feature One</option>
<option value="features/mill.asp"> Millennium Bug</option>
</SELECT><br>

<SELECT NAME="select2" onChange="goToUrl('select2')">
<OPTION SELECTED VALUE="">News</OPTION>
<option value="news/adreport.asp">Report on Net ads</option>
<option value="news/that.asp">Another news item</option>
</select><br>

<SELECT NAME="select3" onChange="goToUrl('select3')">
<OPTION SELECTED VALUE="">Links</OPTION>
<option value="http://www.microsoft.com"> Microsoft</option>
<option value="http://www.netscape.com"> Netscape</option>
<option value="http://www.pcpro.co.uk">A good read!</option>
</select><br>


<input type="Submit" value="Go!">

</form>

The important thing to notice is that each selection box is named, and that name is passed to the JavaScript during onChange. Now you could try and get at the correct select tag automatically from within the JavaScript code, but we've found that this can be problematic due to different flavours of scripting within the various browsers.

Speaking of browser problems, don't make the mistake of removing your Go! button completely. If you do, what will happen when someone without JavaScript support views your site? Maybe they're using an older browser, or they're from a company where all browsers are installed with JavaScript disabled. Whatever the reason, they're going to be stuck on your FrontPage and unable to visit the rest of your site. So, even if you have automated navigation, always leave the Go! button in place.