Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get an Input value using jQuery after a few milliseconds

I want to get the value of an input field and send an ajax request. If I use keyup or keypress or change, the value is available instantly and request is sent. I want to wait for the user e.g. for 1 or 2 seconds so that he types whole word and then send an ajax request. My code is like this to get the vlaue. Thanks.

    var timeout = window.setTimeout(function() {
        $('input#search').keyup(function() {
            var key = $("#search").val();
            console.log(key);
        });

    }, 1000);
    clearTimeout(timeout);
like image 772
rashidkhan Avatar asked Dec 11 '25 21:12

rashidkhan


2 Answers

You need to use a timer and then use clearTimeout it to reset it as the user types. This code will do what you want and here's a jsFiddle.

var Timer;

function Start() {

    $('#TheInput').keyup(function () {

        clearTimeout(Timer);
        Timer = setTimeout(SendRequest, 1000);
    });
}


function SendRequest() {

    var key = $("#TheInput").val();    
    alert(key);
}

$(Start);
like image 80
frenchie Avatar answered Dec 13 '25 11:12

frenchie


Every time you call the function, you should clear the timeout and set a new one, try this:

(function () {
   var timeout = {};
   var update = function () {
     clearTimeout(timeout);
     timeout = setTimeout(function () {
       var key = $('#search').val();
       console.log(key);
     }, 1000);
   };

   $('input#search').keyup(update);
   $('input#search').change(update);
 }());
like image 21
Fernando Avatar answered Dec 13 '25 09:12

Fernando



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!