Skip to content

Instantly share code, notes, and snippets.

@rponte
Last active June 11, 2016 09:13
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rponte/5784478 to your computer and use it in GitHub Desktop.
Save rponte/5784478 to your computer and use it in GitHub Desktop.
Delaying actions on keypress with jQuery
$('#mySearch').keyup(function() {
clearTimeout($.data(this, 'timer'));
var wait = setTimeout(search, 500);
$(this).data('timer', wait);
});
function search() {
$.post("stuff.php", {nStr: "" + $('#mySearch').val() + ""}, function(data){
if(data.length > 0) {
$('#suggestions').show();
$('#autoSuggestionsList').html(data);
}else{
$('#suggestions').hide();
}
});
}
$('#searchString').keyup(function(e) {
clearTimeout($.data(this, 'timer'));
if (e.keyCode == 13)
search(true);
else
$(this).data('timer', setTimeout(search, 500));
});
function search(force) {
var existingString = $("#searchString").val();
if (!force && existingString.length < 3) return; //wasn't enter, not > 2 char
$.get('/Tracker/Search/' + existingString, function(data) {
$('div#results').html(data);
$('#results').show();
});
}