JavaScript / XML based Country, State Selection Script

JavaScript Country Selection listMaking use of my XML based Country and State/Province file I have put together a small script to populate two drop down lists with the complete Country and the selected countries Province or State list.

The code is ALL client-side based, so it will suffer from browsers without JavaScript enabled, but it is a very fast and light weight script to use if you want to quickly add a Country and State selection box to your registration forms. This script does not require any database to function.

Demo page
Download Country/State Code (60)


Code Explanation:
The initial XML Parser script:

if (window.ActiveXObject) 
{
    xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
}
else if (document.implementation && 
document.implementation.createDocument) 
{
    xmlDoc = document.implementation.createDocument("","doc",null);
}
 
xmlDoc.async=false;
 
xmlDoc.load("country_state.xml");

Internet Explorer has had a built in XML parser since version 5, but this parser opens XML files differently to other browsers (Firefox, Opera, etc), so to load an XML file you need to first check which browser is running on the client, For IE:

window.ActiveXObject

and a double check for other browsers:

document.implementation && 
document.implementation.createDocument

If IE exists, create an empty Microsoft XML document object:

xmlDoc = new ActiveXObject("Microsoft.XMLDOM");

Or for Other browsers:

xmlDoc = document.implementation.createDocument("","doc",null);

Once the browser check is done you can now load the XML document, from here on the code works the same in IE as in other browsers. The next bit of code sets asynchronized loading off, to make sure that the parser will not execute the script while the XML document is still loading; :

xmlDoc.async=false;

You can now load the xml document (in this case the Country_State XML file) using the parser that was selected for the browser:

xmlDoc.load("country_state.xml");

On a side note, there is an easy way to test that your XML file has been loaded correctly during development. Just add the document.write or alert function to return the number of nodes in the XML file (in my country_state XML example I would return the number of <country> nodes - with the expected result being 252):

document.write(xmlDoc.getElementsByTagName("country").length);

Once the XML file has loaded correctly, you can perform functions using the file. The next part of my code calls the fillCountryList() function that populates the first select box. I call the fillCountryList() function in my onload() event handler:
HTML:

<body onload="fillCountryList();">

JavaScript:

function fillCountryList ()
{
    var countryList = document.getElementById("cboCountry");
 
    for (var x = countryList.options.length-1; x >-1; x--)
    {
        countryList.options[x] = null;
    }
    var countryNames = xmlDoc.getElementsByTagName("country");
    var numberOfCountries = countryNames.length;
 
    for (var i=0; i<=numberOfCountries-1; i++)
    {
        var currentCountry =  countryNames[i].getAttribute("name");
        fillList(countryList,currentCountry,currentCountry);
    }
}

The fillCountryList() function identifies the first selection box with the specified ID (in my example cboCountry), the function then clears all current entries in the selection box. Clearing entries is good way to prevent duplicate information from being in your selection list prior to processing. On another side note, having VALID data in your selection box is an excellent way to still have your web page form display correctly if JavaScript is disabled on the client; this data can act as an alternative to the JavaScript data; an example of alternative data for the country selection box is listed.
Alternative HTML example:

<select id="cboCountry" onchange="fillStateList();">
        <option value="">Select a Country</option>
        <option value="1">South Africa</option>
        <option value="2">USA</option>
        <option value="3">UK</option>
        <option value="4">Other</option>
</select>

The above code example is NOT a requirement, and my current example does not have any alternative data, but it can help your website to degrade well under different client environments.

The next part of the fillCountryList() function is getting the country names from loaded XML file:

var countryNames = xmlDoc.getElementsByTagName("country");

This will return an object collection for all nodes with the <country> tag to an array in the countryNames variable. A loop then processes the array and adds each country to the cboCountry select box using the fillList() function.

The state select box is only populated once a new country has been selected using the onChange event handler. Note: you should also be able to use the onClick event handler rather than the onChange event handler.

The fillStateList() function populates the States in the same way as the fillCountryList() function does, but first gets the selected countries array ID out of the country array before looping through THAT countries State/Province array therby filling the cboState select box with valid states.

Hopefully this code and explanation will assist beginners and experts alike. Download and enjoy.

This script has been tested under Firefox, Opera, and Internet Explorer 6 & Internet Explorer 7.
Currently NOT working in Safari. Safari processes the “document. getElementsByTagName” function differently to other browsers, I will find a fix and release an updated version of the script soon.

Questions and comments are welcome.

Demo page
Download Country/State Code (60)

License: Creative Commons Attribution 2.5 South Africa License.

Like this post? Share it:
Save to del.icio.us   Digg it!   Share on facebook   Add to my Technorati Favorites   Share on GoGuide   Stumble!   reddit this!   Add to Google Bookmarks   Seed Newsvine   Add to Muti

3 Comments to 'JavaScript / XML based Country, State Selection Script'

Subscribe to comments with RSS or TrackBack to 'JavaScript / XML based Country, State Selection Script'.

  1. Joe Rybacek said,

    I was using your awesome list to populate a database for use in some AJAX scripts and I noticed some duplicates. I’m not sure if you are interested in the revised XML document, but I can zip it up and send it to you.

    Thanks for your extensive work!

    Joe Rybacek

  2. fonbyn said,

    Dude, i have to say, very AWESOME script,excellent XML. And i thank you for posting it. I just put up a bid for this data on a freelance site before i saw your code.

:: Trackbacks/Pingbacks ::

  1. Pingback by Michael John Grove :: One developers guide to sanity :: Blog :: » Three Level XML to Javascript Drop Down List - on June 27th, 2008 at 5:34 pm

Leave a Reply