Hope this is quick and easy for someone to find out. I am new to using a lot of javascript / jquery, and I have the following setting to pull the client name from the database and display it when the user has finished entering the client ID.
Everything works fine, but it searches in every keyboard. I know that I can change it to blur, but I want it to search when they go, with a delay .
Here is the current code:
function postData(){ var id = $('#id').val(); $.post('inc/repairs/events-backend.php',{id:id}, function(data){ $("#display_customer").html(data); }); return false; } $(function() { $("#id").bind('keyup',function() {postData()}); });
As you can see, this is a binding to each keyword, which means that if you search too fast, this may lead to an incorrect result, since it is still loading. (i.e. if no matches are found, an error is displayed, and dial fast enough so that the user needs a backspace and redials the last number)
Can someone help add a delay to the existing code, and, if possible, a little explanation regarding the change you made, I would rather not just copy and paste without understanding.
---- EDIT ----
This is the code I ended up with, thank you guys!
function postData(){ var id = $('#id').val(); $.post('inc/repairs/events-backend.php',{id:id}, function(data){ $("#display_customer").html(data); }); return false; } $(function() { var timer; $("#id").bind('keyup input',function() { timer && clearTimeout(timer); timer = setTimeout(postData, 300); }); });
javascript jquery delay
Tarquin
source share