Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keyup only after last key with jquery

Tags:

jquery

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
    }
});
like image 648
Antonio Ciccia Avatar asked May 09 '12 16:05

Antonio Ciccia


People also ask

How do I delay a Keyup event?

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.

How do you delay the Keyup handler until the user stops typing?

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.

What is the difference between Keyup and Keydown?

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.

What is Keyup event in jQuery?

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.


2 Answers

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); }); 
like image 113
adeneo Avatar answered Nov 02 '22 07:11

adeneo


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.

like image 34
Julie Sheffield Avatar answered Nov 02 '22 08:11

Julie Sheffield