Dynamic Dependant DropDown List: US States & Counties

Posted on November 6, 2008, under JavaScript, jQuery 

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 drop down 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.

Get the script

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.

Comment via Facebook

comments

Leave a Reply


* = required fields

  (will not be published)


XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Note: If you want to post CODE Snippets, please make them postable first!
(e.g. <br /> should be converted to &lt;br /&gt;)

POSTING RULES:

  • The comment must be relevant with the topic of the post.
  • Only comments with real email addresses will get approved. So, emails like 'abc@domain.com' will not be accepted.
  • Do not post the same message in multiple articles through the site.
  • Do not post advertisements, junk mail or pyramid schemes.
  • In case you post a link to another site, please explain briefly where the link goes as a courtesy to other users.
  • Do not post comments such as: "Thank you", "Awesome", "Nice tutorial", "Merci", etc.