Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery search as you type with ajax

Tags:

jquery

i'm trying to create a search where you input text into a textfield and onkeyup it will fire a function off that will send the value of the field to a page and return the results to the div container. The problem i'm having is that when someone is typing, there is a horrible lag going on. I think what's going on is that it's trying to search each letter typed in and does each request. How do i make it so that if i type into the box, wait 1/2 a second (500), if nothing is typed in, then do the ajax search,but if in that time frame another letter comes up, don't even bother with the ajax request. I've been busting my head on this and can't figure it out. All help is appreciated!

// fired off on keyup function findMember(s) {     if(s.length>=3)         $('#searchResults').load('/search.asp?s='+s); } 
like image 361
Damien Avatar asked Apr 25 '12 15:04

Damien


1 Answers

What this will do is clear the timeout on each press, so if 1/2 second hasn't passed the func wont be executed, then set a timer for 500ms again. Thats it, no need to load a big library..

let timeoutID = null;  function findMember(str) {   console.log('search: ' + str) }  $('#target').keyup(function(e) {   clearTimeout(timeoutID);   const value = e.target.value   timeoutID = setTimeout(() => findMember(value), 500) });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="search" id="target" placeholder="Type something" />
like image 175
Dominic Avatar answered Sep 19 '22 15:09

Dominic