Newbie
Newbie

Reputation: 25

How To Load jQuery JSON using onLoad. Obtaining City & State from Zipcode On Form?

I am by no means an expert coder and have been struggling with this all day. I am trying to autofill the city and state based on the zip code in my website's contact form. I have found a nice jQuery thing called Ziptastic. I do a JSON call (I think that's what its called) and this retrieves the data from the Ziptastic website. Here is Ziptastic: http://daspecster.github.com/ziptastic/demo.html

Here is the code I have that pulls the code from the Ziptastic website and enters the city & state into my contact form:

        $(document).on("keyup", "#zip", function(){
          var zip = this.value;
          $.getJSON('http://zip.elevenbasetwo.com/v2/US/' + zip, function(json) {
            $('#city').val(json.city);
          });
          $.getJSON('http://zip.elevenbasetwo.com?zip=' + zip, function(json) {
            $('#state').val(json.state);
          });
        });

My form works well now and is updating my city and state fields after I enter AND KEYUP on the zipcode field. However here is the problem... My website visitor enters their zip-code on my website homepage which is posted to my contact form on this page where I am trying to auto-fill the city and state. I need to click into the field and click out for it to update.

I need the City and State to autofill immediately (onload).

I cannot figure out how to make this code onLoad with the zipcode value that is posted to my contact form from my homepage.

Can someone help?

Thanks

Upvotes: 1

Views: 5311

Answers (2)

Aaron Kurtzhals
Aaron Kurtzhals

Reputation: 2036

$(document).ready(function(){
      var zip = $("#zip").val();
      $.getJSON('http://zip.elevenbasetwo.com/v2/US/' + zip, function(json) {
        $('#city').val(json.city);
      });
      $.getJSON('http://zip.elevenbasetwo.com?zip=' + zip, function(json) {
        $('#state').val(json.state);
      });
 });

Upvotes: 1

Joe
Joe

Reputation: 146

In order to do this with Javascript, you'd have to use the same getJSON code that you've been using, except you'd actually have to echo the value of the POSTed field into the code instead of using + zip... something like this:

$.getJSON('http://zip.elevenbasetwo.com?zip=<?php echo $_POST['zip']; ?>', function(json) {
     $('#state').val(json.state);
});

(assuming you're using PHP here. It would be pretty much equivalent in other languages though; I'm sure you can figure that part out.)

Upvotes: 2

Related Questions