jQuery Cascading Dropdown Menus
One of the trickiest things to do gracefully on a website is create drop-down menus that are dependent on each other (also called cascading drop down menus). There are several ways to do this, of course, but I’ve seen that the most elegant/Web 2.0ish way to go about it is using AJAX calls to a web service or other exterior files. Ajax is a great way to grab data off your server because you DO NOT have to refresh the page once it’s loaded. I stumbled across this script on the jQuery examples page and expanded upon it to make it work the way I needed it to. Note the different types of cascading drop down menus on that site. The idea here is that a particular value in the first menu is selected and the script calls data sitting on the server and does an ad-hoc query to find related items from the JSON-formatted list.
1 | [{"When":"Level_1","Value":"Level_2","Text":"Level_2"}] |
Note how “Level_2″ is only activated when “Level_1″ is selected in the main script.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <script src="js/cascade/jquery.cascade.js" type="text/javascript"></script> <script src="js/cascade/jquery.cascade.ext.js" type="text/javascript"></script> <script type="text/javascript" src="js/cascade/jquery.templating.js" ></script> <script type="text/javascript"> jQuery(document).ready(function() { jQuery("#level_2").cascade("#level_1",{ ajax: {url: 'js/level_2.js' }, template: commonTemplate, match: commonMatch, timeout: 250 //just to show loading indicator }); jQuery("#level_3").cascade("#level_2",{ ajax: {url: 'js/level_3.js' }, template: commonTemplate, match: commonMatch, timeout: 250 //just to show loading indicator }); }); </script> |
In the above example, you’ll note that “Level_3″ is dependent on “Level_2 and “Level_2″ is dependent on “Level_1″ which is the cascading effect we were going for. It doesn’t get much easier than that! As long as the JSON formatted string reflects what you are querying for, i.e. “Level_2″ is dependent on “Level_1″ you’ll be good to go and this script will work like a charm. I’ve managed to get it to work on 6 different cascading levels without any problems at all. The author even added a cool little graphic that displays while the script is loading.
1 2 3 4 5 | <style type="text/css"> .cascade-loading { background: transparent url("graphics/indicator.gif") no-repeat center; } </style> |
There are many, many ways to do this but if you need a data-driven set of cascading drop down menus, I’ve found that this way is incredibly easy to implement and looks nice as well.
More from Adam Estrada
- ESRI Flex Training
- ESRI Flex API without ESRI
- GeoNames and GeoRSS
- Washington DC Mapping Party
- SpatiaLite and Smart Phones
Adam Estrada Recommends
- Adam – The Indian iPad killer (MtaraM)
- 15 Killer Hacks for WordPress that Are Extremely Useful (MtaraM)
- Events of the Past/Future (Maploser)