JavaScript / XML based Country, State Selection Script

JavaScript Country Selection listUPDATE 26 January 2009: Fixed the XML file load Bug that was affecting Chrome and Safari

Making 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

Code Explanation:
The initial XML Parser script:

if (window.ActiveXObject) 
    xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
else if (document.implementation && 
    var xmlhttp = new window.XMLHttpRequest();"GET","country_state.xml",false);
    xmlDoc = xmlhttp.responseXML.documentElement;



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:


and a double check for other browsers:

document.implementation && 

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

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

Or for Other browsers:

    var xmlhttp = new window.XMLHttpRequest();"GET","country_state.xml",false);
    xmlDoc = xmlhttp.responseXML.documentElement;

Once the browser check is done it loads the XML document, from here on the code works the same in IE as in other browsers.

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):


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:


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");

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:

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, Google Chrome and Safari 3.
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.
UPDATE 26 January 2009: Fixed XML file load for Chrome and Safari :- Please drop me a line if you find any bugs that I may have missed.

Questions and comments are welcome.

Demo page

License: Creative Commons Attribution 2.5 South Africa License.

12 thoughts on “JavaScript / XML based Country, State Selection Script

  1. Pingback: Michael John Grove :: One developers guide to sanity :: Blog :: » Three Level XML to Javascript Drop Down List
  2. 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

  3. 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.

  4. Shaun says:

    Hello and thanks alot for all the hard work. There is a problem though with safari. It will not allow the form fields to be populated. I just noticed I have a system update (and safari is included) so I will report back if this fixes the problem.

    current safari version: 3.1.2 (5525.20.1)

  5. Thanks Shaun – I have been meaning to create a fix for the Safari bug (which indecently also exists in Google Chrome) for a while now.
    Your post is the reminder I needed – I will put some time aside shortly to fix it.

  6. Shaun says:

    sorry, had another quick question.

    As a test, I wanted to see how the values passed on form submission. I created a plain old form with method=GET to see and nothing is coming across. Am I missing something?

  7. Hi Shaun – I have managed to fix the bug (I think) please download the new code, or give my demo a test in Safari to see if it is truly working across the board.

    Hope this fix sorts you out.

  8. hello all,

    I am trying to learn and working on one pilot project as part of my studies.

    We are trying to create a drp down menu wherein the visitor comes to the site and has to select a country and then a state and then a city . once he is done this then he should be navigated to the particular page or site of that site. Presume that their are differnt versions of the site for different cities and states and countries…

    CAn anybody help me in this please.. Especially Michale i would be very veyr happy and thankfull if you can try to help me . i am a complete new and a student in the university . and this is our project.

    Kindly send the script and how to implement this in php using mysql database. to my email id *******@****.***

    Thanks & Regards

  9. I would be happy to assist you and your group with getting your system perfect, but I am not going to develop the entire system or part of it for you.

    If you send me a copy of the code you have already completed in trying to get your system working, I will be happy to point you in the right direction to get it finished.

  10. Ashley says:

    Michael, great script! This has helped me a great deal with a project I am working on that required a long list of data and no server-side scripting. One thing I’ve been trying to do is get it to accept a URL as the value of the option so that the selection in the second drop down is a link to an external site. Any direction on how I could do that? Thanks!

Comments are closed.