javaScript zipcode auto fill code example
Example: javaScript zipcode auto fill
<script type="text/javascript"><![CDATA[
$(function() {
var clientKey = "js-9qZHzu2Flc59Eq5rx10JdKERovBlJp3TQ3ApyC4TOa3tA8U7aVRnFwf41RpLgtE7";
var cache = {};
var container = $("#example1");
var errorDiv = container.find("div.text-error");
function handleResp(data)
{
if (data.error_msg)
errorDiv.text(data.error_msg);
else if ("city" in data)
{
container.find("input[name='city']").val(data.city);
container.find("input[name='state']").val(data.state);
}
}
container.find("input[name='zipcode']").on("keyup change", function() {
var zipcode = $(this).val().substring(0, 5);
if (zipcode.length == 5 && /^[0-9]+$/.test(zipcode))
{
errorDiv.empty();
if (zipcode in cache)
{
handleResp(cache[zipcode]);
}
else
{
var url = "http://www.zipcodeapi.com/rest/"+clientKey+"/info.json/" + zipcode + "/radians";
$.ajax({
"url": url,
"dataType": "json"
}).done(function(data) {
handleResp(data);
cache[zipcode] = data;
}).fail(function(data) {
if (data.responseText && (json = $.parseJSON(data.responseText)))
{
cache[zipcode] = json;
if (json.error_msg)
errorDiv.text(json.error_msg);
}
else
errorDiv.text('Request failed.');
});
}
}
}).trigger("change");
});
]]></script>