Run javascript function when user finishes typing instead of on key up?

前端 未结 29 2024
我寻月下人不归
我寻月下人不归 2020-11-22 04:03

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 wo

相关标签:
29条回答
  • 2020-11-22 04:27

    If there is necessity for the user to move away from the field, we can use "onBlur" instead of Onchange in Javascript

      <TextField id="outlined-basic"  variant="outlined" defaultValue={CardValue} onBlur={cardTitleFn} />
    

    If that is not necessary setting timer would be the good option.

    0 讨论(0)
  • 2020-11-22 04:29

    Yes, you can set a timeout of say 2 seconds on each and every key up event which will fire an ajax request. You can also store the XHR method and abort it on subsequent key press events so that you save bandwith even more. Here's something I've written for an autocomplete script of mine.

    var timer;
    var x;
    
    $(".some-input").keyup(function () {
        if (x) { x.abort() } // If there is an existing XHR, abort it.
        clearTimeout(timer); // Clear the timer so we don't end up with dupes.
        timer = setTimeout(function() { // assign timer a new timeout 
            x = $.getJSON(...); // run ajax request and store in x variable (so we can cancel)
        }, 2000); // 2000ms delay, tweak for faster/slower
    });
    

    Hope this helps,

    Marko

    0 讨论(0)
  • 2020-11-22 04:29

    For passing parameters to your function along with ES6 syntax.

    $(document).ready(() => {
        let timer = null;
         $('.classSelector').keydown(() => {
         clearTimeout(timer); 
         timer = setTimeout(() => foo('params'), 500);
      });
    });
    
    const foo = (params) => {
      console.log(`In foo ${params}`);
    }
    
    0 讨论(0)
  • 2020-11-22 04:31

    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();
            });
        };
    }]);
    
    0 讨论(0)
  • 2020-11-22 04:32

    The chosen answer above does not work.

    Because typingTimer is occassionaly set multiple times (keyup pressed twice before keydown is triggered for fast typers etc.) then it doesn't clear properly.

    The solution below solves this problem and will call X seconds after finished as the OP requested. It also no longer requires the redundant keydown function. I have also added a check so that your function call won't happen if your input is empty.

    //setup before functions
    var typingTimer;                //timer identifier
    var doneTypingInterval = 5000;  //time in ms (5 seconds)
    
    //on keyup, start the countdown
    $('#myInput').keyup(function(){
        clearTimeout(typingTimer);
        if ($('#myInput').val()) {
            typingTimer = setTimeout(doneTyping, doneTypingInterval);
        }
    });
    
    //user is "finished typing," do something
    function doneTyping () {
        //do something
    }
    

    And the same code in vanilla JavaScript solution:

    //setup before functions
    let typingTimer;                //timer identifier
    let doneTypingInterval = 5000;  //time in ms (5 seconds)
    let myInput = document.getElementById('myInput');
    
    //on keyup, start the countdown
    myInput.addEventListener('keyup', () => {
        clearTimeout(typingTimer);
        if (myInput.value) {
            typingTimer = setTimeout(doneTyping, doneTypingInterval);
        }
    });
    
    //user is "finished typing," do something
    function doneTyping () {
        //do something
    }
    

    This solution does use ES6 but it's not necessary here. Just replace let with var and the arrow function with a regular function.

    0 讨论(0)
  • 2020-11-22 04:32
    var timer;
    var timeout = 1000;
    
    $('#in').keyup(function(){
        clearTimeout(timer);
        if ($('#in').val) {
            timer = setTimeout(function(){
                //do stuff here e.g ajax call etc....
                 var v = $("#in").val();
                 $("#out").html(v);
            }, timeout);
        }
    });
    

    full example here: http://jsfiddle.net/ZYXp4/8/

    0 讨论(0)
提交回复
热议问题