2

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.

4 Answers 4

1

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)
            errorDiv.text(data.error_msg);
        else if ("city" in data)
        {
            // Set city and state
            container.find("input[name='city']").val(data.city);
            container.find("input[name='state']").val(data.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
            errorDiv.empty();

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

                // Make AJAX request
                $.ajax({
                    "url": url,
                    "dataType": "json"
                }).done(function(data) {
                    handleResp(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(json.error_msg);
                    }
                    else
                        errorDiv.text('Request failed.');
                });
            }
        }
    }).trigger("change");
});

//]]>

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.

2
  • 1
    What does this code do, and how does it answer the actual question? Commented Sep 9, 2016 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
    Commented Sep 10, 2016 at 18:31
0

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) {
            showLocation(field.val());
        }
        else
            showLocation("");
    });

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

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.

4
  • how it can fetch city name or state when it is not exist in database it can fetched by depend on zipcode Commented Oct 29, 2015 at 7:56
  • check Autocomplete By Zip Code. here explains it with a custom module.
    – Abin
    Commented Oct 29, 2015 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
    Commented Oct 29, 2015 at 17:23
  • itz not a big deal tim, u can create that custom module. there a lots of tutorials available
    – Abin
    Commented Oct 30, 2015 at 4:05
0

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 and acknowledge you have read our privacy policy.

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