Developer

Stupid Web Tricks: Dynamic drop-down menus

Need to dynamically change the values in one drop-down based on selections in another? Stupid Web Tricks has the answer with our complete working JavaScript example.

Click here for our complete list of Stupid Web Tricks.

Like most Americans, I'm geographically challenged, so much so that it once took me an hour to find the snack bar in my hotel. The worse part is that I'd been in the same snack bar less than 24 hours before. Maybe that's why I've got real problems dealing with Web pages that require me to select cities and states. I usually find myself picking invalid combinations, like putting the town of Metuchen in the state of Pennsylvania.

So I created a test page that takes into account the fact that I could get lost going around the block. The available options are limited based upon the client's input. For example, if you select "Metuchen" as the city, then "New Jersey" is automatically selected for the state. And if the client selects the state first, then only cities valid for that state are displayed.

This functionality is accomplished in JavaScript through the use of the options array and the Option() constructor. The options array is used to access the various options of an HTML select and can also be used to remove all of a select's options by setting the length property to 0. The option constructor has four parameters: text, value, default selected, and selected.

That's really all there is to it. Listing A shows the complete solution to my affliction.

Editor's Picks