Autofill City & State from Zip Code with Ziptastic

Most address fields on web forms ask for city, state, and zip code (or city and post code, outside of the US). But as us nerds often lament, city and state are redundant with zip code. Or at least they can be inferred from a correctly entered zip code. That's the kind of thing computers are good at. What we need is a proper API to cough up that information for us on demand.

jQuery: Ajax the data

Yeah so jQuery. We used it above to make event handling on the input easier, but it's really need here because of its ability to make ajax calls with error handling sixty two times easier than doing it with vanilla JavaScript.

After the passed validation, we can make the Ajax call. All we give it for data is the zip code we've collected and we get some JSON back which is trivially easy to access the city and state and apply them as values to the appropriate inputs.

Of course we can validate all day long for the valid format of zip codes, but not every 5 digit integer is a zip code. Should we ask Ziptastic for a zip code that doesn't exist, it will return an error. In that case we just show an error message.

Demo and Download

Snag the ZIP. GET IT?! Also, if someone wants to apply some actually nice UX and design to this, I'd be happy to update the demo with credit.Andru Stoicescu at Better <html> submitted a bit of a fancier design so I updated to that.

Notes

I'm not going to tell you this is bulletproof. Addresses are hard. I heard some zip codes cross state lines.

Ziptastic is US only.Just days after publishing this, Ziptastic starts supporting postal codes internationally.Zippopotamus is similar and supports 60 counties.

Usually those with tricky zip codes are typically aware of it already. For instance, my sister lives in Maplewood, MN and has the zip code of 55109. She borders St. Paul, MN and almost every time you put 55109 in (forms, maps, etc) it returns St. Paul, MN.

One small improvement I would make is to move $(“.zip-error”).hide(); to just before the ajax call.

Without this change, it could get confusing to the user if they enter an incorrect zip, and then try to correct it. Even after correction, the error message is still visible until the ajax callback is received.

With the change, the error message disappears after entering a 5-digit integer and while waiting for the callback.

Found a problem, should be easy to solve, though: It doesn’t play nice with ZIP codes starting with 0 – for instance, all of Vermont begins with 05 – I’m 05641 (Barre, VT). Entered, doesn’t register. Tried again with 01234 (Boston/Bedford, MA) and also no joy. My guess is the script is ignoring leading 0s.

Bit of a loaded question. You’d need a data set of locations and their center coordinates (or centroids).

You then take the centroid of the location you’re interested in (let’s say San Francisco, CA). You can calculate a bounding box (which is just 4 coordinates representing each corner of the box). You’d then run a query against the data set for other centroids that are within your calculated bounding box.

I find out the latitude / longitude of the entered post code, then do a calculation on the database query comparing it to those stored (If you have them stored), that way you can do like X stores near Y post code, as once you’ve got the distance worked out, you can do a where in the select to whatever distance you want specified, e.g. 50 miles, 100, etc.

Definitely love this demo, but I wonder if this introduces some usability questions? If I come to a web form, expecting to see an address form, but only see a zip code field, I may (mistakenly) believe that the form didn’t load properly or that the page is broken.

I realize this is a demo, so I’m not trying to call this out as being ‘wrong’. But as a suggestion for an actual application of this pattern, you should look at including some microcopy that says “Hey! Just enter your zip code and we’ll take care of the city and state stuff!”

True, you could do that, and that’s probably what I would do: using Javascript, apply a class to the form/form elements in order to have those fields fade out.

I would just be afraid that by going this route you would need to display the fields in the traditional order: the city and state fields would come before the zip code field. To do otherwise would introduce another potentially jarring usability hiccup. So if you keep the traditional order, you run the risk of users ignoring the microcopy (not the developer’s fault, I realize), and entering the items in order (1. city, 2. state, 3. zip), rending this method useless for this use case. Again, not the end of the world if you go this happens. And the user ignoring both your copy and visual clues is probably a fringe case. I’m just kind of thinking out loud here…

Especially so for place names that contain punctuation etc. having the matching zip code is a matter of clean data, to make sure that there was no typo (say in the zip code) and so that you can mine clean data. It’s also a waste of people’s time entering the same (full address) information all the time in forms. Hence proper automated assistance in this regard is most welcome, and people don’t get frustrated filling it in. Frustration with forms can lead to loss in sales, if you have client facing sign-up or order forms.
All the forms where you have to repeat a lot of already known information (because you’ve been given an identifier) is a pain we can do without. If you added up all the wasted time filling in duplications of data for all systems in the world, it would be many lifetimes worth of time…essentially stemming from inadequate data collection and processing systems. And many lifetimes are spent cleaning up dirty data that shouldn’t be.
…quietly stepping off pedestal.

I’d like to comment on this approach as one coming from the address verification industry. I’m a developer at SmartyStreets, where I’ve had a good deal of experience with USPS address quality products.

Thanks for noting that “addresses are hard”, and that ZIP Codes cross state boundaries. I can take that statement further and say that while ZIP Codes do cross State lines (very rarely), they very often cross City and County lines. It is also quite common for a ZIP Code to have alternate names assigned by the USPS which are valid (and often more appropriate than the default) for use when mailing, as well as some alternate names which are NOT appropriate for use when mailing. My perusing of the code reveals that Ziptastic isn’t taking this into account (“SELECT * FROM zipcodes WHERE zipcode=’$zip’ LIMIT 1″ isn’t going to cut it).

Another concern I have with a service like Ziptastic is the underlying data source. The Ziptastic database contains just over 80,000 records, which is about right considering the alternate names I mentioned, but it concerns me that there is no reference in the Ziptastic repository that shows where the ZIP Code data was acquired (please correct me if I’ve missed something). If it was purchased from a 3rd-party, is it licensed to be posted in a public repository such that other people have open access to it? How often does he update it? ZIP Codes are added and removed on a monthly basis by the USPS.

In the end, I respect the authors of Ziptastic–they are working towards solving a real challenge on the web in simplifying UX and reducing user error. I’m concerned that this simplistic approach is creating a false sense of security for those who choose to employ it in their applications. The truth is that the only way to be sure of the correct City/State/ZIP Code combination is to verify an address as a whole, using a CASS-Certified address verification service.

Dude… every place I look all I see is you spamming for Smartystreets.
I won’t use your product just due to sheer annoyance at this point.
You’re getting market saturation, but you’re also spamming the hell out of every message thread I’ve found.

I think you are right. I read about it some days ago and it has something to do with the same origin policy. The jQuery documentation says:

“Due to browser security restrictions, most ‘Ajax’ requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, or protocol.”

But this policy is browser dependent and maybe thats the reason why the demo dosn’t work at all in my Firefox (407 Proxy Authentication Required). I think there are some ways to get around this problem, but I’m not sure if they are used here.

There is no workaround for that – I tried a lot of things and finally came out with a server CURL :). Only one thing makes me doubt about my thoughts – JSON. May be AJAX with JSON is allowed on non-origin domains. Chris, could you clarify this, please.

Looked through some articles – yes, the reason is that you are using JSON. It really IS allowed to use asynchronous cross-domain JS requests. You opened a new thing for me in JQuery/Javascript. It changes a lot of things :) Thanks a lot

I’m confused – does this not already exist in the US? When I buy goods on the net here in the UK, I usually only have to provide a house number/name and my post code, and the address (street name, city/town, country etc) is auto-filled. It’s been around for probably at least 5 years?

@chris – as you point out: addresses are hard. I think I have a bit of an answer for this but can’t code it for you. A bit of a sore point for us, we paid a substantial amount for a therapeutic bed which “couldn’t” be delivered because their computer didn’t recognize the zip code that our area had been changed to 11 months prior (no kidding). Recovery attempts escalated to the point of involving TV’s “get Gephardt” (ombudsman) and got us a free bed. Still 5 years later I find some gas-pumps don’t recognize our zip because of (you guess).

The PO system is free, and liable, to change boundaries and numbers at their discretion so AT BEST this should only be thought of as something to ‘pre-fill’ a DEFAULT field. 1) ask ZIP first (so most people fill it); 2) expand fields – with pre-filled (if possible) fields; 3) IF integer, regex, AJAX fails: provide “we don’t recognize that zip” warning; but, 4) always allow, and never prevent user’s manual entry.

Demo doesn’t work for me with our local zipcodes like 90260, 90278, etc.. Tried FF 12 and IE8

I tried the demo with 90260 (my ZIPCODE) and immediately upon entering the 5th/last digit, it gives an error statement “Not a real zip code.” Tried a few other known valid zips, same error. Also ignored error, pressed enter key & it clears the field, with no display of city, state (do see empty fields that instantly disappear).

Until recently we used Google maps to solve this. Still looking for good alternatives. For some projects we also need geolocation so best choice for now seems to be setting up our own Nominatim install with data from openstreetmap.org

Hi Chris,
I’ve been following your articles and learn so much from it. Thanks for being one of my inspiration in creating beautiful websites. Looking forward for your other articles that really helped me a lot.

we need a product that will enter the zip code …i have name, address, town and state…just looking for the zip…does a product like this exist? thank you~laura

This comment thread is closed. If you have important information to share, you can always contact me.

Treehouse is where you go to learn HTML, CSS, and how to build iOS apps. It's a complete education in modern web and app technology, designed to get you ready for a hot new job or to kickstart your own business.

The Lodge is a member login only area with access to video training on how to build websites from scratch using the best modern tools.

What now? I have some ideas for you.

Go explore CodePen!

As a front end designer and developer, you should have an account on CodePen so you can save your snippets, present your ideas, and engage with other front end folk. I'd encourage you to go PRO as well, to unlock the full power of CodePen.

Get the newsletter!

You should sign up for the CSS-Tricks newsletter. It's a clean copy of all the blog posts each week, combined together, right to your inbox. If email isn't your thing, there is an RSS feed, iTunes, and lots of other ways to subscribe.

Listen to ShopTalk!

Subscribe to The Lodge!

The Lodge is a members-only, ad-free video learning area here on CSS-Tricks. Just like the free screencasts, but organized into four large complete series. Membership is also the #1 best way to support CSS-Tricks.

We can do the real footer now.

Site Links

Colophon

CSS-Tricks* is created, written by, and maintained by Chris Coyier. It is built on WordPress, hosted by Media Temple, and the assets are served by MaxCDN. The fonts are Source Sans and Source Code Pro. It is made possible by viewers like you who subscribe to The Lodge and through advertising for products and services I like.