Dynamic Dependant DropDown List: US States & Counties

I was googling for a way to show a drop down menu with states that populates another menu with counties from the selected state. I found a nice dynamic dependent dropdown script (with categories & subcategories) at dreamwebstore.com. However, adding over 2000 counties in a single JavaScript file is not such a good idea because such a script is quite big (200KB+) and in many cases (a slow internet connection, some downloads in progress etc.) it will take some time to load.

I’ve decided to keep the counties from each state in separate files. For instance, if we select Hawaii state (with 5 counties), only the hi.js file will load which has only a size of 515 bytes. To do this I’ve used the powerful JavaScript library JQuery.

Dependent DropDown Select Element

This is the HTML file that we will use to show the dropdowns:

The HTML File

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
 <head>
  <title>Dynamic DropDowns with US States & Counties</title>

<!-- Style -->

<link rel="stylesheet" type="text/css" href="style/style.css" />

<!-- JQuery JS -->
<script type="text/javascript" src="js/jquery-1.2.6.min.js"></script>

<!-- Drop Down JS -->
<script type="text/javascript" src="js/drop_down.js"></script>

<!-- Preload Images -->

<script type="text/javascript">

<!--
pic1 = new Image(16, 16);
pic1.src="style/loader.gif";
//-->
</script>

</head>

<BODY>

<div align="center">

<strong>DEMO</strong>
Select a state and see how the county drop down changes based on your selection
</div><br />
<form name="form">
<table width="317" border="0" align="center">

   <tr>
     <td width="100">State</td>
     <td width="217">
<select id="state" name="state">

<option value='AL'>Alabama</option>
<option value='AK'>Alaska</option>
<option value='AZ'>Arizona</option>
<option value='AR'>Arkansas</option>
<option value='CA'>California</option>

<option value='CO'>Colorado</option>
<option value='CT'>Connecticut</option>
<option value='DE'>Delaware</option>
<option value='DC'>District of Columbia</option>
<option value='FL'>Florida</option>

<option value='GA'>Georgia</option>
<option value='HI'>Hawaii</option>
<option value='ID'>Idaho</option>
<option value='IL'>Illinois</option>
<option value='IN'>Indiana</option>

<option value='IA'>Iowa</option>
<option value='KS'>Kansas</option>
<option value='KY'>Kentucky</option>
<option value='LA'>Louisiana</option>
<option value='ME'>Maine</option>

<option value='MD'>Maryland</option>
<option value='MA'>Massachusetts</option>
<option value='MI'>Michigan</option>
<option value='MN'>Minnesota</option>
<option value='MS'>Mississippi</option>

<option value='MO'>Missouri</option>
<option value='MT'>Montana</option>
<option value='NE'>Nebraska</option>
<option value='NV'>Nevada</option>
<option value='NH'>New Hampshire</option>

<option value='NJ'>New Jersey</option>
<option value='NM'>New Mexico</option>
<option value='NY'>New York</option>
<option value='NC'>North Carolina</option>
<option value='ND'>North Dakota</option>

<option value='OH'>Ohio</option>
<option value='OK'>Oklahoma</option>
<option value='OR'>Oregon</option>
<option value='PA'>Pennsylvania</option>
<option value='RI'>Rhode Island</option>

<option value='SC'>South Carolina</option>
<option value='SD'>South Dakota</option>
<option value='TN'>Tennessee</option>
<option value='TX'>Texas</option>
<option value='UT'>Utah</option>

<option value='VT'>Vermont</option>
<option value='VA'>Virginia</option>
<option value='WA'>Washington</option>
<option value='WV'>West Virginia</option>
<option value='WI'>Wisconsin</option>

<option value='WY'>Wyoming</option>
</select>
	 </td>
   </tr>
   <tr>
     <td height="33">County</td>

     <td><div id="county_drop_down">
	 <select id="county" name="county"><option value="">County...</option></select>
	 </div>

	 <span id="loading_county_drop_down">
	 <img src="style/loader.gif" width="16" height="16" align="absmiddle">&nbsp;Loading...
	 </span>

	 <div id="no_county_drop_down">This state has no counties.</div></td>
   </tr>
 </table>
 </form>
</body>

</html>

In the head section of the page I’ve included the JQuery library, the JS Drop Down County Changer file, some JavaScript to preload the GIF loader image (which appears instantly when you select a state and wait for the county drop down to show) and some CSS code that hides some parts of the HTML when we initially load the page (i.e.: the county drop down loader).

JavaScript Drop Down Counties Loader (drop_down.js)

function drop_down_list()
{
  var state = $('#state').val();

    // Alaska and District Columbia have no counties
    if(state == 'AK' || state == 'DC')
    {
    $('#county_drop_down').hide();
    $('#no_county_drop_down').show();
    }
    else
    {
    // Show the Loading...
    $('#loading_county_drop_down').show(); 

    // Hide the drop down
    $('#county_drop_down').hide();

    // Hide the "no counties" message (if it's the case)
    $('#no_county_drop_down').hide();

    $.getScript("js/states/"+ state.toLowerCase() +".js", function(){

    populate(document.form.county);

    // Hide the Loading...
    $('#loading_county_drop_down').hide();

    // Show the drop down
    $('#county_drop_down').show();
  });
}
}

$(document).ready(function(){
$("#state").change(drop_down_list);
});

$(window).load(drop_down_list);

How it works?

When DOM is ready and a selection is made from the state dropdown, the drop_down_list() function is called. In this case the change event is triggered.

$(document).ready(function(){
$("#state").change(drop_down_list);
});

The states District of Columbia and Alaska have no counties. If the user selects any of them the county drop down disappears and in its place a message is shown, notifying the visitor that there aren’t any counties for the selected state:

$('#county_drop_down').hide(); // Hide Counties Drop Down
$('#no_county_drop_down').show(); // Show the 'no_county_drop_down' DIV

If a state with counties is selected, the script hides the previous selected drop down (and the ‘no counties’ message if it’s the case) and shows a loading message until the new drop down is loaded:

$('#loading_county_drop_down').show(); // Show the Loading...

$('#county_drop_down').hide(); // Hide the drop down
$('#no_county_drop_down').hide(); // Hide the "no counties" message (if it's the case)

$.getScript("js/states/"+ state.toLowerCase() +".js", function(){

populate(document.form.county);

 	 $('#loading_county_drop_down').hide(); // Hide the Loading...
	 $('#county_drop_down').show(); // Show the drop down
});

One important aspect is the usage of the load event:

$(window).load(drop_down_list);

When the page loads first time, it automatically takes the already selected value from ‘state’ and fills the county dropdown by calling drop_down_list().

Counties JavaScript File

Here’s the content of a JS file that contains counties:

hi.js (Hawaii)

function populate(form)
{
form.options.length = 0;
form.options[0] = new Option("Select a county of Hawaii","");
form.options[1] = new Option("Hawaii County","Hawaii County");
form.options[2] = new Option("City & County of Honolulu","City & County of Honolulu");
form.options[3] = new Option("Kalawao County","Kalawao County");
form.options[4] = new Option("Kauai County","Kauai County");
form.options[5] = new Option("Maui County","Maui County");
}

The populate() function resets the counties drop down (form.options.length = 0;) and populates it with new values.

Download Dynamic Dependant DropDown

You can get the whole package with the US States and Counties. Additionally, the ZIP file also contains a bonus: a version of the application that works with MySQL database. The `states` and `counties` are stored in a database. The SQL data can be easily imported using a PHP file from the package.

Download

Comment via Facebook

comments

88 Comments

  1. says

    Does anyone know how to get this to work in a wordpress page? I am using the template page route ie, page-test.php and followed tutorials to register and use wp_enqueue_scripts. As long as the scripts go in the header this works fine on a page outside of wordpress. I am currently using a file outside of wordpress and incorporating my theme files by using and it works fine this way but I want it to work within a wordpress page if at all possible.

    What do I need to do to get this to work inside of a wordpress page?
    Sorry for my ignorance but js and jquery are like a foriegn language that I do not know. The problem is obviously wordpress specific because this works fine outside of wordpress. Please help.

    I currently am using this at http://ididntsee.com/share-your-story.php <–outside wordpress and it works.
    I am trying to get it to work at http://ididntsee.com/page/ <–inside wordpress and it does not work.

  2. Alex Riemann says

    Thanks so much for the script… I m using the classic version and it works. However, I would like to know if there is some way I can keep the selected values of the county dropdown after form submission and redirection to error messages.
    Thanks in advance!

    • Gabriel C.Gabriel C. says

      You can keep them by either using sessions ( in PHP it would be something like: <?php session_start(); $_SESSION['county'] = $_POST['county']; ?> in the page where the POST values are sent to ) or pass them in the URL bar or through POST forms (they can be added as hidden fields).

  3. Stan says

    I would just like to thank you for sharing this dropdown menu. I’ve been looking all over for a solution such as this. The world needs more people like you.

    Stan K

  4. Rudy says

    I’m with Garfield a few posts up…for adding new data it’s awesome. When I go into EDIT mode, I’d love to be able to “turn off” the auto-load and leave it with a “on change” mode.

    JavaScript hates me, so I’m not sure how to do this. :)

  5. Angelo says

    I used the php version of the script and works great…
    But i ran into a small problem..
    Is there a way to have a default option value of .
    The script automatically loads all the counties of a state what if i want to make a query in all counties?

  6. thiyaku says

    Its works..but i cant get value from country dropdown in asp.net using c#..
    why… how can i get value and text from country ….pls as soon as fast…

  7. JoeyB says

    Great script, will save me hours of work. How can i set this up either default to a certain state or default to something like “Choose”. Rather than everytime the page loads it comes up to Alabama and Autauga County?

  8. Garfield says

    Hi, great script.
    I had a quick question. I was able to make the script work and add values to a database. However, it’s on a form and when I access the previous entries, the data for my state field is nicely populated but since the county field is automatically updated onpage load, it overwrites the info coming from the database and fills the county dropdown with the options for it’s corresponding state. Any suggestions?

  9. says

    Gabriel

    I was able to make the script work on one page, but not on a second. I changed line 28 in the js file to read the name of the form, but it does not work.

    I even copied and made a second js file and changed the name in case there was some conflict, but that did not work.

    It seems that I am only able to get it to work when there are no other input fields in the form.

    Ultimately I want to be able to choose more than one county.

    Any advice you can offer?

    Thank you

    Gary

  10. Erik Torres says

    Great script, how would I add a third dependent list box? dependent from the selection on the second list box…

    • Gabriel C.Gabriel C. says

      You will have to create a second function similar to drop_down_list() and trigger it when the second drop_down is selected.

      Under $("#state").change(drop_down_list); you could add $("#county").change(drop_down_list_two);

      AND Make sure you change all the IDs to be unique ๐Ÿ˜‰

  11. says

    Thank you for this wonderful script!

    I am using Drupal and trying to integrate this into a some sort of form builder where users can enter data, including their state/county. Any suggestions on how to get this integrated? I unfortunately have no idea… any advice is GREATLY appreciated! Thank you so much!

    Sincerely,
    Eric G.

    • Gabriel C.Gabriel C. says

      So you want to integrate the script without any changes to a form builder. Is that correct? Is the form builder page available for everyone or only for logged in users? Can you share me the URL to that page?

      • says

        That is correct. The form builder will only be available to registered logged in members. I do not yet have this active on a URL but I am using Drupal 6 and am trying to integrate it into the Webform/Form Builder module, both of which offer JQuery support (which I believe is what I need in order to do this?) – is there anything I can provide you so you have a better vision of what’s going on? This integration is really important for our functionality and I truly appreciate your assistance!

        Happy Thanksgiving!
        Eric G.

  12. says

    We are looking for a solution where you have 8 dropdowns and you can choose to start in any of the dropdowns and the others are dynamically updated.
    Does anyone knows where I can find such a solution?

    //Mats

  13. says

    Gabriel-

    I downloaded and installed- I’d like to add another select list for my country’s – I have these in a database as well as the db tableobtrusive select list

    what js script would I use to do the following:
    customer selects country value US displays state and county select lists other wise hidden ie UK

  14. John says

    I can’t get your code to work in WordPress. It’s driving me nuts! I even bought your package just to make sure i had the right code.

    I have 2 identical pages in the same folder: page.html (regular page that doesn’t run under WordPress) and a page dynamically made via WordPress (made from a Page Template that has your html inside of it)

    The html version runs fine. The WP version gives me the spinning gif and the “loading…” text. When i look at the source code for each page, they are identical. Well, relative paths to the js files are a bit different, but the links are correct)

    Any idea what’s going on?

    • Gabriel C.Gabriel C. says

      @John, first of all thanks for buying the package. The setup of this script does require some basic knowledge of HTML and JavaScript (even PHP if you use the code that works with a MySQL database) to install it, whether you want to make it work with WordPress, Joomla or any other PHP Script. I am not saying that you don’t have it but some things can be tricky and as you said “it drove you nuts”. I am willing to help you setup the script on your WordPress blog, free of charge. Just write me at support [ @ ] bitrepository ( . ) com to discuss more about it ๐Ÿ˜‰

    • John says

      For anyone trying to get it to work with WordPress, here is what i did:

      The drop_down.js file has a line that points to one of the states .js files. In WP, you need the full path to begin with: /states….

      And because i don’t know how to mix php with a javascript “file”, i had to put all the drop_down.js code inside the actual web page, and not linked.

  15. Adrienne says

    It works beautifully locally, but it stops working when I upload it to a server. The state dropdown displays and the “loading” message appears for the county dropdown, but the little gif spinner keeps spinning and spinning and the county dropdown never loads. I did customize it, but I left all the names, ids and the like the same so it should work and it does locally anyway. Here’s where I’m using it (http://www.voiceofwomensgolf.com/preview/adminAdd1.php). Any ideas why it would work locally and stop working when I upload it on a server? Any help or advice you can provide would be greatly appreciated.

    • Gabriel C.Gabriel C. says

      I noticed that you made some changes to the drop-down. It doesn’t contain the states list anymore. If you can give me FTP access to the location where you have installed the script, I can make make it work in exchange of a small fee. If you are still interested, let me know.

      • says

        it works up to:

        $.getScript(“/states/”+ state.toLowerCase() +”.js”, function(){

        it keeps spinnig… i commented out the getScript function call to the jquery and place the show outside the function call and the drop_down.js worked fine its the getScript call which is not working??

        • Gabriel C.Gabriel C. says

          Works fine for me. I’ve noticed that you changed the path to make it work. I’ve suspected that this may be the problem in the first place. Just let me know if you have any other problems/questions.

          • says

            thanks… thanks… just disregard my previous messages…. it works excellent i am using the database version with cgi not with PHP its works very good thanks again…

  16. says

    I’m sorry I never returned a remark to your message. I have been traveling. I am new to setting up a website and have not tried out your state and county code yet. Attempt to do so will be made in several days. I will let you know if it works out. Thank You.

  17. Angelie says

    Hi! Thanks for the script! We’ve used it in the site us-hometours.com but looks like that it takes forever to load the counties. Can you please give me an idea on how to resolve this performance issue?

    • Gabriel C.Gabriel C. says

      Actually, it doesn’t populate the County DropDown. Check line 28 from drop_down.js:

      populate(document.form.county);

      It tries to populate any data to the form that has the name “form” and the county element. The form that has the id “searchform” should be named “form”. If you want to give a different name to it, such as “search_form” then update line 28 too:

      populate(document.search_form.county);

      Good luck!

      • Angelie says

        My bad! I was like “googling” for hours, tried different ways to cache the js files. >_<
        Thanks much! Appreciate the quick response. Good luck too! :)

    • Dennis says

      I was wondering if anyone has fixed the part where you select an option from the 3rd selection box to take you to a url or better yet print some info on the page..

  18. says

    Mitch,

    I pulled the full list from the census.gov site. I don’t recall exactly where I found it, but if you like I can share with you a tab-delimitted text file or an SQL insert code if that would be helpful. Contact me via dgran at duanegran -dot- com.

  19. says

    I am working on something very similar to this.

    I’ve put all the states in a mysql table, and all the counties in another table, linked by state_id.

    Over 3100 counties. yuck.

    Any idea how to build this particular part of a form using mysql/javascript/php?

  20. ruffone says

    function drop_down_list() {
    var country = $(‘#countries’).val();

    switch (country) {
    // No country is selected.
    case ”:
    $(‘#country_drop_down’).hide();
    $(‘#loading_country_drop_down’).hide();
    $(‘#no_selection_drop_down’).show();
    break;
    // Countries that has no state.
    case ‘AL':
    case ‘DC':

    $(‘#country_drop_down’).hide();
    $(‘#loading_country_drop_down’).hide();
    $(‘#no_country_drop_down’).show();
    break;
    // Load file for selected country.
    default :
    $(‘#loading_country_drop_down’).show(); // Show the Loading…

    $(‘#country_drop_down’).hide(); // Hide the drop down
    $(‘#no_country_drop_down’).hide(); // Hide the “no counties” message (if it’s the case)
    $(‘#no_selection_drop_down’).hide();

    // ToDo: Check it script exist and respond appropriately if it is not.
    // This would be a good thing to do considering there is so many countries
    // it will take time to generated all the files. If the file was not present
    // the page would not freeze up. I do not know how to achieve this.
    $.getScript(“js/countries/” + country.toLowerCase() + “.js”, function() {

    populate(document.form.states);

    $(‘#loading_country_drop_down’).hide(); // Hide the Loading…
    $(‘#country_drop_down’).show(); // Show the drop down
    });
    break;
    }

    }
    $(document).ready(function() {
    $(“#countries”).change(drop_down_list);
    });

    $(window).load(drop_down_list);

  21. ruffone says

    if no selection is made (if the selected value is ”) I want to say “No value was selected” so I added a new CSS called the “no_selection_drop_down”. I want to still show the “no_country_drop_down”. How do I add both to the if statement.

  22. Stacie says

    I need to redirect to a URL after the County is selected. Does anyone have a working example or idea how I could accomplish this?

  23. Duane Gran says

    Where did you get the source data? For my needs I need to construct the js dynamically from a source, preferably a yml file. Can you direct me to where one would get a parsable source of counties by state?

Leave a Reply

Your email address will not be published. Required fields are marked *