In the United States, cities are split up by a unique 5 digit zip codes (postal code). This postal code in turn tells what city and state it is from. Therefore it is redundant to type the city and state.

Is there a way, with the Address Field module, to autofill the city and state if a postal code is submited?

This then leads to the second question, how to force a correct postal code entry. By default a user can type any text and it will be accepted.


Here is Javascript code that uses zipcodeapi.com API:

<script type="text/javascript">//<![CDATA[
$(function() {
    // IMPORTANT: Fill in your client key
    var clientKey = "js-9qZHzu2Flc59Eq5rx10JdKERovBlJp3TQ3ApyC4TOa3tA8U7aVRnFwf41RpLgtE7";

    var cache = {};
    var container = $("#example1");
    var errorDiv = container.find("div.text-error");

    /** Handle successful response */
    function handleResp(data)
        // Check for error
        if (data.error_msg)
        else if ("city" in data)
            // Set city and state

    // Set up event handlers
    container.find("input[name='zipcode']").on("keyup change", function() {
        // Get zip code
        var zipcode = $(this).val().substring(0, 5);
        if (zipcode.length == 5 && /^[0-9]+$/.test(zipcode))
            // Clear error

            // Check cache
            if (zipcode in cache)
                // Build url
                var url = "http://www.zipcodeapi.com/rest/"+clientKey+"/info.json/" + zipcode + "/radians";

                // Make AJAX request
                    "url": url,
                    "dataType": "json"
                }).done(function(data) {

                    // Store in cache
                    cache[zipcode] = data;
                }).fail(function(data) {
                    if (data.responseText && (json = $.parseJSON(data.responseText)))
                        // Store in cache
                        cache[zipcode] = json;

                        // Check for error
                        if (json.error_msg)
                        errorDiv.text('Request failed.');


You can see an example here - http://www.zipcodeapi.com/Examples#example1

Since the question is how to autofill a valid city and state based on the user entering a zipcode first, the above Javascript code does that. Click on the example above to see how it works.

  • 1
    What does this code do, and how does it answer the actual question? – Pierre.Vriens Sep 9 '16 at 16:01
  • The question was how to autofill a valid city and state based on the user entering a zipcode first. The code is Javascript that does that. Click on the example above to see how it works. – Bob Bickel Sep 10 '16 at 18:31

For this you can develop your own custom module using dependencies on address field .

  1. You need to define a server function that will return the city and state in JSON based on a zip code.
  2. Subscribe to change, keyup and input events on an input field.
  3. Define a JavaScript function that will call the server function using AJAX. On the success function, you set the fields using the response.

Helping code

$("#txtZipCode").bind("change keyup input", function (e) {
        var field = $(this);
        if (field.val().length === 5) {

function showLocation(zipCodeValue) {
    var txtCity = $("#city");
    var txtState = $("#state");
    if (zipCodeValue.toString().length != 5) {
    else {
            dataType: "json",
            url: "Location/GetZipCode",
                    zipCodeNumber: zipCodeValue
            success: function (data) {

May be Entity reference autofill will help you to achieve this functionality. There is a remark in project page about this.

Addressfield: Addressfield needs some additional processing in order to be loaded. A sub-module is included to make it work. Enable "Entity reference autofill addressfield" and you're good to go.

I didnt tested this, just found while searching.

Hope this will help you.

  • how it can fetch city name or state when it is not exist in database it can fetched by depend on zipcode – Adi Oct 29 '15 at 7:56
  • check Autocomplete By Zip Code. here explains it with a custom module. – Abin Oct 29 '15 at 8:27
  • thank you Abin for the helpful link! unfortunately i don't have the skills to create that module. If anyone is willing to help me figure it out that would be great! – Anon Ymous Oct 29 '15 at 17:23
  • itz not a big deal tim, u can create that custom module. there a lots of tutorials available – Abin Oct 30 '15 at 4:05

You might check out this new module from Lush and give it a review in the process.

Address Field Lookup: https://www.drupal.org/sandbox/danielmrichards/2580615

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.