620

I want to trigger an ajax request when the user has finished typing in a text box. I don't want it to run the function on every time the user types a letter because that would result in A LOT of ajax requests, however I don't want them to have to hit the enter button either.

Is there a way so I can detect when the user has finished typing and then do the ajax request?

Using jQuery here!

5
  • 27
    I think you'll need to define "finish typing" for us. Nov 18, 2010 at 22:14
  • 8
    While @Surreal Dreams' answer satisfies most of your requirements, if the user starts typing again AFTER the specified timeout, multiple requests will be sent to the server. See my answer below which stores each XHR request in a variable and cancels it before firing off a new one. This is actually what Google does in their Instant search.
    – Marko
    Nov 18, 2010 at 22:33
  • The chosen answer is incorrect for a few reasons: 1. It always fires after 5 seconds even if user is typing. 2. It doesn't wait until user has finished typing as requested. 3. It fires multiple requests as mentioned by @Marko above. See my corrected answer below.
    – going
    May 8, 2011 at 10:28
  • 1
    What about blur? I guess the user has definitely finished typing when the input element loses focus.
    – Don P
    Aug 31, 2016 at 19:54
  • 11
    A simple google search could've gotten you the simple answer: schier.co/blog/2014/12/08/…
    – Cannicide
    Feb 22, 2018 at 0:54

34 Answers 34

1
2
0

Not a direct answer bu if someone looking for an AngularJS solution. I wrote a directive according to the popular solutions here.

 app.directive("ngTypeEnds", ["$timeout", function ($timeout) {
    return function (scope, element, attrs) {
        var typingTimer;               
        element.bind("keyup", function (event) {
            if (typingTimer)
                $timeout.cancel(typingTimer);
            if (angular.element(element)[0].value) {
                typingTimer = $timeout(function () {
                    scope.$apply(function () {
                        scope.$eval(attrs.ngTypeEnds);
                    });
                }, 500);
            }
            event.preventDefault();
        });
    };
}]);
1
  • You should also add an example of how to use the directive in template. Aug 15, 2022 at 11:18
0

You guys have heard of closures in javascript ?!

it's very simple and straightforward just compare you current input value with the old value that the setTimeOut function closes over, and voila, you're done.

let timer;
$('#myInput').on('keyup', function() {
  window.clearTimeout(timer);
  // here is the closures javascript magic happens.
  const value = $(this).val();
  timer = setTimeout(() => {
    if(value === $(this).val() && $(this).val()!== ''){
        alert($(this).val());
    }
  }, 500);
})
0

I needed mine to run for a specific control and this worked for me :

function debounce(func, timeout) {
            let timer;
            return (...args) => {
                clearTimeout(timer);
                timer = setTimeout(() => { func.apply(this, args); }, timeout);
            };
        }

$('#txtFilterClientCode').keyup(debounce(function () {
            console.log("Test");
        }, 1000));
-2

Wow, even 3 comments are pretty correct!

  1. Empty input is not a reason to skip function call, e.g. I remove waste parameter from url before redirect

  2. .on ('input', function() { ... }); should be used to trigger keyup, paste and change events

  3. definitely .val() or .value must be used

  4. You can use $(this) inside event function instead of #id to work with multiple inputs

  5. (my decision) I use anonymous function instead of doneTyping in setTimeout to easily access $(this) from n.4, but you need to save it first like var $currentInput = $(this);

EDIT I see that some people don't understand directions without the possibility to copy-paste ready code. Here you're

var typingTimer;
//                  2
$("#myinput").on('input', function () {
    //             4     3
    var input = $(this).val();
    clearTimeout(typingTimer);
    //                           5
    typingTimer = setTimeout(function() {
        // do something with input
        alert(input);
    }, 5000);      
});
3
  • How this answers the question? Jun 13, 2017 at 7:12
  • @ThomasOrlita this answer supplements 3 most rated answers. Take a look at accepted one: 1. it doesn't support paste, it doesn't use this, etc. (I think it's important but I don't want to get lost in tons of comments)
    – vladkras
    Jun 13, 2017 at 16:37
  • 1
    This does not answer the question. If you would like to comment about another answer, there is a commenting system (I'm using it right now!)
    – GrayedFox
    Sep 2, 2019 at 21:50
1
2

Not the answer you're looking for? Browse other questions tagged or ask your own question.