Phone: 501.851.2880
Email: arkansas@softwyre.com

  

Javascript City/State/Zip Selector.

One of our clients recently needed to implement a search based on a users location.  We were using Drupal 7, location module to implement this but currently this module only allows proximity search based on a zipcode.  We wanted the user to be able to use a select box to select the state, which would then populate the cities in another select box, which would then populate the zip code in order for the location module to do the search.

 

There are a few solutions that are close to this.  http://jqueryui.com/demos/autocomplete/#remote-jsonp shows how to use jquery ui to do an ajax lookup on the geonames web service.  This would work but I found that the responsiveness of the geonames free service to be slow and inconsistent.  The free service also limits you to 30,000 searches a day or 2,000 an hour.  This is a lot for a small application but is still just another dependency that I would rather do without.

I found a free database of city zipcodes here: http://federalgovernmentzipcodes.us/ and parsed it with a ruby script to produce a couple of javascript arrays.  It turns out that all the city/state/zip combinations can be stored in a javascript file 1.1mb in size.

At this point you can fairly easily use jquery to add the necessary events to a form field so that it will automatically populate the states from the stored array, then it will automatically populate the city from the selected state, then it will automatically populate the zip from the selected city.  Alternatively, if the user enters a zip code it will automatically populate the city and state.  Since this is all done in javascript it should work in any CMS or custom code.

You can download the code here: citystatezip-js.zip

It requires jquery and works in all the major browsers including ie6.  I included the ruby script in case you need to customize the js arrays with other data.

Add comment


Security code
Refresh

Back to top