I have some code that fires a function on keyup inside an input field. To prevent this function from firing every literal keyup I set a timeout function of half a second so my code won't spam ajax requests.
But for some reason this timeout code isn't working.
This is what I had at first, which does work:
Form:
<form class="search-address">
<input id="account_id" type="hidden" name="account_id" value="<?PHP echo $_SESSION['user']['id']; ?>">
<input class="search-word" type="text" placeholder="Zoeken in adresboek...">
</form>
My trigger code:
$('.search-word').keyup(function(e) {
clearTimeout($.data(this, 'timer'));
if (e.keyCode == 13){
search(true);
}else{
$(this).data('timer', setTimeout(search, 500));
}
});
My function:
function search(force) {
var zoekwaarde = $(".search-word").val();
var account_id = $("#account_id").val();
$.ajax({
type:'post',
url:"includes/searchaddress.php",
data:({zoekwaarde: zoekwaarde, account_id: account_id}),
success:function(data){
$( "#adressenlist" ).show().empty().append( data );
$( "#deleteresult" ).hide();
$( "#adresresult" ).hide();
}
});
}
This works, but the problem is I have 2 forms with the same class of .search-word
. So I tweaked my code a little like this:
$('.search-word').keyup(function(e) {
searchword = $(this).val();
clearTimeout($.data(this, 'timer'));
if (e.keyCode == 13){
search(true, searchword);
}else{
$(this).data('timer', setTimeout(search(true, searchword), 500));
}
});
function search(force, searchword) {
var zoekwaarde = searchword;
var account_id = $("#account_id").val();
$.ajax({
type:'post',
url:"includes/searchaddress.php",
data:({zoekwaarde: zoekwaarde, account_id: account_id}),
success:function(data){
$( "#adressenlist" ).show().empty().append( data );
$( "#deleteresult" ).hide();
$( "#adresresult" ).hide();
}
});
}
I use searchword = $(this).val();
so I only post the value of $(this)
input field, and not the last one in the dom tree. I thought this would work but this breaks my timeout function, it now triggers the search
function instantly on every key press. What can I do to fix that?