JSFiddle - React, Tailwind, and code Playground
by John Doe
HTML
<div class="hero-unit">
<h2>Zippoptamus</h2>
<br>
<p>Try entering a zip code like <b>90210</b> Beverly Hills, CA!</p>
<br>
<form action="#" method="post" class="form fancy-form">
<fieldset>
<legend>US Address Autocompletion</legend>
<br>
<div>
<div id="zipbox" class="control-group">
<label for="zip">Zip</label>
<input type="text" class="" pattern="[0-9]*" name="zip" id="zip" placeholder="Type your ZIP code">
</div>
</div>
<div>
<div id="citybox" class="control-group" style="display: none;">
<label for="city">City</label>
<input type="text" name="city" id="city" placeholder="">
</div>
<div id="statebox" class="control-group" style="display: none;">
<label for="state">State</label>
<input type="text" name="state" id="state" placeholder="">
</div>
</div>
<div>
<!--<a href="http://api.zippopotam.us/static/sample_us.html" class="btn btn-success btn-large">Submit</a>-->
</div>
</fieldset>
</form>
</div>
JavaScript
$(function() {
$(document).ready( function()
{
$('#citybox').hide();
$('#statebox').hide();
});
// OnKeyDown Function
$("#zip").keyup(function() {
var zip_in = $(this);
var zip_box = $('#zipbox');
if (zip_in.val().length<5)
{
zip_box.removeClass('error success');
}
else if ( zip_in.val().length>5)
{
zip_box.addClass('error').removeClass('success');
}
else if ((zip_in.val().length == 5) )
{
// Make HTTP Request
$.ajax({
url: "http://api.zippopotam.us/us/" + zip_in.val(),
cache: false,
dataType: "json",
type: "GET",
success: function(result, success) {
// Make the city and state boxes visible
$('#citybox').slideDown();
$('#statebox').slideDown();
// US Zip Code Records Officially Map to only 1 Primary Location
places = result['places'][0];
$("#city").val(places['place name']);
$("#state").val(places['state']);
zip_box.addClass('success').removeClass('error');
},
error: function(result, success) {
zip_box.removeClass('success').addClass('error');
}
});
}
});
});
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-30975659-1']);
_gaq.push(['_setDomainName', 'zippopotam.us']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();