Optimised search using Ajax and keypress

45,685

Solution 1

You can do something like this:

$('#searchString').keyup(function(e) {
    clearTimeout($.data(this, 'timer'));
    if (e.keyCode == 13)
      search(true);
    else
      $(this).data('timer', setTimeout(search, 500));
});
function search(force) {
    var existingString = $("#searchString").val();
    if (!force && existingString.length < 3) return; //wasn't enter, not > 2 char
    $.get('/Tracker/Search/' + existingString, function(data) {
        $('div#results').html(data);
        $('#results').show();
    });
}

What this does is perform a search (on keyup, better than keypress for these situations) after 500ms by storing a timer on the #searchString element's .data() collection. Every keyup it clears that timer, and if the key was enter, searches immediately, if it wasn't sets a another 500ms timeout before auto-searching.

Solution 2

See this older question:

How do I make my live jQuery search wait a second before performing the search?

Solution 3

What I would do is each key press use a setTimeout function with the desired delay. So that function will fire after that timeout. Each key press then delete the timer and set a new one, with clearTimeout();

See here for some examples, scrolling past all the adverts.

http://www.elated.com/articles/javascript-timers-with-settimeout-and-setinterval/

Share:
45,685

Related videos on Youtube

leora
Author by

leora

Updated on February 21, 2020

Comments

  • leora
    leora over 4 years

    I have the following code that I want to use to search a database as a user is typing into a textbox. The code below works fine but it seems a little inefficient, as if a user is typing really fast. I am potentially doing many more searches than necessary. So if a user is typing in "sailing", I am searching on "sail", "saili", "sailin", and "sailing".

    I wanted to see if there was a way to detect any particular time between keypresses so only search if user stops typing for 500 milliseconds or something like this.

    Is there a best practice for something like this?

    $('#searchString').keypress(function(e) {
    
        if (e.keyCode == 13) {
    
            var url = '/Tracker/Search/' + $("#searchString").val();
            $.get(url, function(data) {
                $('div#results').html(data);
                $('#results').show();
            });
        }
        else {
    
            var existingString = $("#searchString").val();
            if (existingString.length > 2) {
                var url = '/Tracker/Search/' + existingString;
                $.get(url, function(data) {
                    $('div#results').html(data);
                    $('#results').show();
                });
            }
        }
    
  • Deepak Thomas
    Deepak Thomas over 11 years
    If anyone's facing trouble with this code, check this out: stackoverflow.com/a/1171758/849829
  • Joab Mendes
    Joab Mendes almost 9 years
    The typing-and-search is working for me, but when i press enter it reloads the page. Why it would be happening?
  • John Christian De Chavez
    John Christian De Chavez almost 9 years
    @JoabR2D2 maybe you have a <form> tag/parent of your <input type='text'>
  • Joab Mendes
    Joab Mendes almost 9 years
    @JohnChristianDeChavez yeah it was there, but i have to keep the form and I'm using a prevenDefault() to solve it.
  • John Christian De Chavez
    John Christian De Chavez almost 9 years
    @JoabR2D2 then your e.preventDefault() is not working because it redirects to your form action try return false maybe. or better dont use a <form> tag if its not really necessary.
  • Joab Mendes
    Joab Mendes almost 9 years
    No, it solved the problem. it's working now. Thanks anyway. o/
  • Derk Jan Speelman
    Derk Jan Speelman over 5 years
    Using input instead of keyup is even better. It not only covers paste or cut actions from the user, it's also faster.
  • Pochmurnik
    Pochmurnik over 4 years
    Describe your solution direct on SO.