Last active
August 29, 2015 14:20
-
-
Save sventech/89818a3a758dcf34cd27 to your computer and use it in GitHub Desktop.
JavaScript update city, region / state location info from https://zippopotam.us free API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// update_inputs = {"city": "#cityInput", "region": "#regionInput", } | |
window.updatePostalCode = function(country, postal_code, update_inputs) { | |
jQuery.get("http://api.zippopotam.us/" + country + "/" + postal_code, "", | |
function( data ) { | |
var result = | |
{ "country": data["country"], | |
"country_code": data["country abbreviation"], | |
"region": data['places'][0]['state'], | |
"city": data['places'][0]['place name']}; | |
if("region" in update_inputs && result["region"]) { | |
$(update_inputs["region"]).val(result["region"]); | |
$(update_inputs["region"]).change(); | |
console.log("update region from postal code"); | |
} | |
if("city" in update_inputs && result["city"]) { | |
$(update_inputs["city"]).val(result["city"]); | |
$(update_inputs["city"]).change(); | |
console.log("update city from postal code"); | |
} | |
}); | |
}; | |
// usage example | |
$( "#inputZipCode" ).change(function() { | |
var postal_code = $("#inputZipCode").val(); | |
if(postal_code.length > 2) { | |
var clean_postal = postal_code.split(" ")[0]; | |
var country_code = $("#inputCountry").val(); | |
window.updatePostalCode(country_code, clean_postal, {"city": "#inputCity", "region": "#inputRegion"}); | |
console.log(clean_postal); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment