The context:
I have a form that asks for a zipcode, state, and city. Next to each input field I have two spans, one that shows a green checkmark if the input is good, and one that shows a red x if the input is bad. Naturally only one is visible at any given time.
<input type="text" id="Zip" class="form-control">
<span id="ZipOK" style="display:none;" class="glyphicon glyphicon-ok"></span>
<span id="ZipBad" style="display:none;" class="glyphicon glyphicon-remove"></span>
<input type="text" id="State">
<span id="StateOK" style="display:none;" class="glyphicon glyphicon-ok"></span>
<span id="StateBad" style="display:none;" class="glyphicon glyphicon-remove"></span>
<input type="text" id="City">
<span id="CityOK" style="display:none;" class="glyphicon glyphicon-ok"></span>
<span id="CityBad" style="display:none;" class="glyphicon glyphicon-remove"></span>
I have a function that detects input to the zip field and then does a database call to get the state and city from the zip code and auto fill the form.
jQuery('.form-control').keyup(function(){
validateZipcode();
});
This is the function that does the ajax, autofills the state/city and hides/shows the appropriate feedback spans.
function validateZip() {
zip = $('#Zip').val();
if (zip.length === 5 && $.isNumeric(zip)) {
$.ajax({
type:"POST",
url: '?report=ajax&request=getStateAndCityFromZip',
data:"Zip="+encodeURIComponent(zip),
success: function(output) {
output = $.parseJSON(output);
if (output['State'].length > 0 && output['City'].length > 0) {
$('#State').val(output['State']);
$('#City').val(output['City']);
$('#StateOK').fadeIn();
$('#StateBad').hide();
$('#CityOK').fadeIn();
$('#CityBad').hide();
$('#ZipOK').fadeIn();
$('#ZipBad').hide();
} else {
$('#ZipOK').hide();
$('#ZipBad').fadeIn();
}
},
error: function (xhr, ajaxOptions, thrownError) {
}});
} else {
$('#ZipOK').hide();
$('#ZipBad').fadeIn();
}
}
The problem:
This code works as is, however there are some instances where if I put in the zip code extremely fast, both the #ZipBad
and #ZipGood
spans will end up visible. Typing at relatively normal or slow pace results in expected behavior.
I assume this has something to do with asynchronous calls to validateZip(), but I don't really know enough about javascript to know how to fix this. Does anyone have any ideas?