admin管理员组

文章数量:1318579

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);

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);
Share Improve this question edited May 24, 2015 at 12:07 frenchie 52k117 gold badges319 silver badges527 bronze badges asked May 24, 2015 at 0:38 rashidkhanrashidkhan 4729 silver badges24 bronze badges 3
  • 1 This is not the best approach if you're hoping to deliver a positive user experience. You can never be sure that the user is done typing just because you have waited an arbitrary number of seconds. Some people type awfully slow. You should consider either a button next to the form which triggers the ajax request, or listen for the "enter" key in the text field and make the request then. – Vince Commented May 24, 2015 at 0:43
  • Thank you for your ment.I've added a submit button but I also want to trigger an ajax request when user inputs something. I just want to trigger ajax request after 1 or 2 seconds. – rashidkhan Commented May 24, 2015 at 0:47
  • @VCode: google search autoplete works without a button – frenchie Commented May 24, 2015 at 3:53
Add a ment  | 

2 Answers 2

Reset to default 7

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);

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);
 }());

本文标签: javascriptGet an Input value using jQuery after a few millisecondsStack Overflow