O'Reilly logo

JavaScript & DHTML Cookbook by Danny Goodman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Using a select Element for Navigation

NN 2, IE 3

Problem

You want users to choose a destination from a pop-up list originating from a <select> tag.

Solution

You have a few scripting possibilities for this solution, depending on your design and scripting style, but they all rely on the select element having been outfitted with option elements containing the URL for each destination. You can display any text you like that is visible in the list, but assign the URL for each item to the value attribute of each option:

<select name="chooser" id="chooser">
    <option value="">Choose a Destination:</option>
    <option value="http://www.megacorp.com/index.html">Home</option>
    <option value="http://www.megacorp.com/products/index.html">Products</option>
    <option value="http://www.megacorp.com/support/index.html">Support</option>
    <option value="http://www.megacorp.com/contact.html">Contact Us</option>
</select>

Some event must trigger the navigation action. The most backward-compatible approach is to locate a clickable button or "Go" icon next to the select element. The onclick event handler of that button or link-surrounded image invokes a function that reads the selected option's value property:

function navigate( ) {
    var choice = document.forms[0].chooser;
    var url = choice.options[choice.selectedIndex].value;
    if (url) {
        location.href = url;
    }
}

Perhaps more convenient for users is to trigger the navigation by making the choice from the list, in which case, you can create a generic (reusable) function ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required