Perform action after user stops typing with Jquery

Asked

Viewed 8,624 times

4

I’m doing a search suggest where after the user type at least 4 letters in the input he does via Ajax the search with the suggestions for the user. But currently after the user has typed the first 4 letters of the word a new Ajax request is made for each typed letter and I would like the Ajax requests to be made only after the user has stopped typing in the input. Follow the source:

 <script type="text/javascript">
     (function(){
          'use strict';

          $('#search').keyup(function(){
               var $this = $(this);
               var valueSeach = $this.val()

               if(valueSeach.length >= 4){
                   $.ajax({
                      url: "consulta.php",
                      dataType: "json",
                      data: {
                          acao: 'autocomplete',
                          parametro: valueSeach
                      },
                      success: function(data) {
                          response(data);
                      }
                  });
               }                                                        
          });
      })();
  </script>

1 answer

7


It is quite complicated to identify when the user has stopped typing, what you can do is to put an interval to perform the research of your suggestion.

An example of this would be counting 1 seconds after the event keyUp so if it stayed 1 seconds without typing a new character you can perform the request and get the suggestions.

Example:

var typingTimer; //timer identifier
var doneTypingInterval = 1000; //time in ms, 1 second for example

//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() {
  console.log('parei de digitar');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="text" id="myInput">

More details: Run Javascript Function when User Finishes Typing

Browser other questions tagged

You are not signed in. Login or sign up in order to post.