Keyup only after last key with jquery

后端 未结 3 1705
忘掉有多难
忘掉有多难 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条回答
  • 2021-02-05 06:55
    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);
    });
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-05 06:59

    I think if you do this with onchange event you don't need to put time interval checks. whenever you complete your input and change the focus. it triggers onchange event for you

    $("input").onchange(function()
    {
       //extract database info
    }
    
    0 讨论(0)
提交回复
热议问题