Keyup only after last key with jquery

后端 未结 3 1709
忘掉有多难
忘掉有多难 2021-02-05 06:14

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

3条回答
  •  猫巷女王i
    2021-02-05 06:56

    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.

提交回复
热议问题