I'm coding a simple script to extract database informations on input keyup event.
The problem i have is that the keyup event is always repeated everytime the user press a key. How can i make it working only after the last key pressed?
I think i should use a function like setTimeOut() after every keyup, But i don't know how... can you make me a simple example please?
Sorry for my bad english :)
Here is what i was trying to do:
$("input").keyup(function()
{
var timer=setTimeout(function() {
}, 1000);
if(!timer)
{
//do .post ajax request
}
});
In this article, we will see how to use keyup with a delay in jQuery. There are two ways to achieve the same: Approach 1: Using the keypress(), fadeIn(), delay() and fadeOut() methods in the jQuery library and clearTimeout() and setTimeout() methods in native JavaScript.
Use a variable to store the timeout function. Then use clearTimeout() to clear this variable of any active timeout functions, and then use setTimeout() to set the active timeout function again.
The keydown event occurs when the key is pressed, followed immediately by the keypress event. Then the keyup event is generated when the key is released.
The keyup event occurs when a keyboard key is released. The keyup() method triggers the keyup event, or attaches a function to run when a keyup event occurs. Tip: Use the event. which property to return which key was pressed.
var timer; $("input").on('keyup', function() { clearTimeout(timer); //clear any running timeout on key up timer = setTimeout(function() { //then give it a second to see if the user is finished //do .post ajax request //then do the ajax call }, 1000); });
You're basically there. You just need to clear the timer if they enter another letter; otherwise, your callback will execute after the 1000 ms regardless of whether they keep typing.
Something like this should work:
$("input").keyup(function (event)
{
var self = this;
if (self.timer)
clearTimeout(self.timer);
self.timer = setTimeout(function ()
{
self.timer = null;
alert(self.value);
}, 1000);
});
Where I just have the alert, you'd put your ajax code to write back to the server.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With