I have been reading a lot of answers on here about deferred techniques on getJSON/ajax requests but nothing seems to fit my scenario. I am making a search input return a set of results based on a getJSON call after 4 characters. This is to limit the amount of results returned, and also the amount of ajax requests (open to more effective solutions).
search_input.on('keyup', function() {
var string = $(this).val();
var quiet_chars = 4;
if(string.length < quiet_chars) {
// Simple notifications function which passes a message to a div, and optional class
notification('Type '+(quiet_chars - string.length)+' more characters to search');
}
if(string.length == quiet_chars) {
notification('Searching...', 'loading');
$.getJSON('stores/stores-search/'+string, function(data) {
// Loop through data and build list....
$('.search_results').html('<ul>'+list_html+'</ul>');
// Function which shows/hides list items based on Jquery :contains
searchResults(string);
});
}
if(string.length > quiet_chars) {
searchResults(string);
}
});
The specific problem I am facing is if you quickly type in 5 (more than 4) characters, the if(string.length > quiet_chars)
condition is met before $('.search_results').html('<ul>'+list_html+'</ul>');
has executed, and tells the user there are no search results.
I need to meet the if(string.length > quiet_chars)
condition to continue filtering the returned results, but only after the list has been appended to the DOM from the getJSON request. Thanks.