Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autofilling state and city based on zip code

I am new to web development and I ran into an issue with a registration form that I'm building for our business. I am using this guide: http://css-tricks.com/using-ziptastic/. This is my first experience with AJAX and JSON and I just can't get the city and state to autofill as soon as I'm done typing in the zip code. Any solutions/suggestions/alternatives will be much appreciated. I set up a basic jsfiddle to test everything out: http://jsfiddle.net/7VtHc/

HTML:

<p>Zip Code: <input type="text" id="zip" /></p>
<p>City: <input type="text" id="city" /></p>
<p>State: <input type="text" id="state" /></p>

jQuery, etc.

$("#zip").keyup(function() {
var el = $(this);

if ((el.val().length == 5) && (is_int(el.val()))) {
    $.ajax({
    url: "http://zip.elevenbasetwo.com",
    cache: false,
    dataType: "json",
    type: "GET",
    data: "zip=" + el.val(),
    success: function(result, success)

    $("#city").val(result.city);
    $("#state").val(result.state);
    });
}
});
like image 849
user3361043 Avatar asked Mar 21 '14 16:03

user3361043


1 Answers

This should work for you. http://jsfiddle.net/7VtHc/5/
I will added that === in JavaScript will check that type are the same. See Here.
There is no need to create an is_int() function.

$(document).ready(function() {
    $("#zip").keyup(function() {
        var el = $(this);

        if (el.val().length === 5) {
            $.ajax({
                url: "http://zip.elevenbasetwo.com",
                cache: false,
                dataType: "json",
                type: "GET",
                data: "zip=" + el.val(),
                success: function(result, success) {
                    $("#city").val(result.city);
                    $("#state").val(result.state);
                }
            });
        }
    });
});

P.S. When you create a JSFiddle make sure you include jQuery from the menu on the right.

like image 118
Ashley Medway Avatar answered Sep 21 '22 08:09

Ashley Medway