Implementing a Hierarchical Navigation with a Selection List


for (var i=0; i<links.length; i++) {   elements["urls"].options[     elements["urls"].options.length] =       new Option(links[i].title, links[i].url); } 

Two selection lists can be paired to provide a hierarchical navigation on a site. The first selection list contains several categories; when a category is selected, the second list contains a set of elements in this category.

From a JavaScript point of view, a list of elements must be maintained and the lists must be filled according to the selection in the first (category) list. So here is the list of links, in JSON format (see Chapter 11, "AJAX (and Related Topics)" for more information on this notation).

var data = {   "search" : [     {"title": "Google", "url": "http://www.google.com/"},     {"title": "MSN", "url":"http://search.msn.com/"}   ],   "browsers" : [     {"title": "Firefox", "url": "http://www.mozilla.com/firefox/"},     {"title": "Opera", "url": "http://www.opera.com/"}   ] }; 


Then, the following code adds options to the second selection list, by using the Option constructor (syntax: first the caption, then the value):

A Hierarchical Navigation (navigation.html; excerpt)

<script language="JavaScript"   type="text/javascript"> function loadElements(f) {   with (f) {     var category = elements["categories"].options[       elements["categories"].selectedIndex].value;     if (category != "") {       var links = data[category];       elements["urls"].options.length = 0;       elements["urls"].options[0] =         new Option("Please select...", "#");       for (var i=0; i<links.length; i++) {         elements["urls"].options[           elements["urls"].options.length] =           new Option(links[i].title, links[i].url);       }     }   } } </script> <form>   <select name="categories"     onchange="loadElements(this.form);">     <option value="">Please select...</option>     <option value="search">Search Engines</option>     <option value="browsers">Browsers</option>   </select>   <select name="urls" onchange="loadURL(this);">   </select> </form> 

Figure 8.9 shows what happens when the first category (search engines) is selected: The second list fills with available options.

Figure 8.9. Selecting an option in the first list fills the second list.





JavaScript Phrasebook(c) Essential Code and Commands
JavaScript Phrasebook
ISBN: 0672328801
EAN: 2147483647
Year: 2006
Pages: 178

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net