Three Level XML to Javascript Drop Down List

Following a post on an Internet forum, here is a small expansion on my Country / State dropdown selection script to enable a third level drop down. This additional level would allow for a country / state / city drop down selection on an XML file as apposed to just a country / state drop down selection.


I have broken the code in this post into its three sections; the HTML, the XML and an external JavaScript file. All of the code can be downloaded here: [download#2].

A section of the HTML code:

...

Country slection - with State/Province select

The XML code:




 
     New York
     New Jersey    
 
 
     Sanfransico
     Hollywood    
 


 
     Johannesburg
     Pretoria    
 
 
     Durban
     Pietermaritsburg    
 

A section of the Javascript code:

...
function fillStateList()
{
 var stateList = document.getElementById("cboState")
 
 for (var x = stateList.options.length-1; x >-1; x--)
 {
     stateList.options[x] = null;
 }
 
 var countryListSelected = 
document.getElementById("cboCountry").selectedIndex;
 var numberStates = 
xmlDoc.getElementsByTagName("country")[countryListSelected]
.getElementsByTagName("state").length;
 
 for (var i=0; i<=numberStates-1; i++)
 {
      var currentState =  
xmlDoc.getElementsByTagName("country")
[countryListSelected].getElementsByTagName
("state").getAttribute("name");
     fillList(stateList,currentState,currentState);
 }
 
}

function fillCityList()
{
 var CityList = document.getElementById("cboCity")
 
     for (var x = CityList.options.length-1; x >-1; x--)
 {
     CityList.options[x] = null;
 }
 var countryListSelected = document.getElementById
("cboCountry").selectedIndex;
 var StateListSelected = document.getElementById
("cboState").selectedIndex;
 var numberCities = xmlDoc.getElementsByTagName("country")
[countryListSelected].getElementsByTagName("state")
[StateListSelected].getElementsByTagName("city").length;
 
     for (var i=0; i<=numberCities-1; i++)
 {
       var currentCity =  xmlDoc.getElementsByTagName("country")
[countryListSelected].getElementsByTagName("state")
[StateListSelected].getElementsByTagName("city").firstChild.nodeValue;
     fillList(CityList,currentCity,currentCity);
 }
}

In a real world situation a full world wide city level dissection of data should not be stored in an single XML file as the amount of entries would place too much load on the XML file -More than likely the XML file would not load. To store all the city names across the world the use of a database to hold the data, and call the required data as needed, would better suit the needs.

This script can be used for any XML file in a similar format to handle multiple levels of data and placing the data into drop down lists.

The complete code for this example can be downloaded here: [download#2]

Have fun and happy coding.