2

I do a search by the js for my site.

Their code it might look like: have a form and when the keyup event, it will send post to a file and retrieve data from that file into the html of a div crazy.

but this yourself in trouble. I find the example for "a" is about 3000 results. for example, take a second to send post. so I press "c" will now send the post to the file is "ac" and there are 100 such results takes 0.3 seconds. eg time I press the letter "a" to "c" 0.2 seconds, it should show results "ac" at 0.5 seconds. then 0.5 seconds later it is the result of "a". ~> Find "ac" into finding "a" So how do you now when you press "c" then it stopped send post with the value "a" that send post with value "ac".

<form method="post" onsubmit="return checkForm(this.form)">
<div class="search padding">
    <input type="text" id="searchbox" name="manga_name" class="input" value="Tìm truyện muốn đọc ..." onfocus="if (value =='Tìm truyện muốn đọc ...'){value =''}" onblur="if (value ==''){value='Tìm truyện muốn đọc ...'}" />
    <input type="submit" value=" " id="searchsubmit" class="go"/>
</div>
    </form>

<div id="result"></div>

And the script:

<script>
$('#searchbox').keyup(function() {
 search();
});

function search() {
var keyword = $('#searchbox').val();
if (keyword != "") {
$('#result').html(loadingText);
$('#result').css('display', 'block');
$.post('/search/',{"keyword":keyword}, function(data){
if (data != "")
{
$('#result').html(data);
}
else
{
$('#result').html('');
$('#result').css('display', 'none');
}
});
}
else {
$('#result').html('');
$('#result').css('display', 'none');
}
}
</script>
TRR
  • 1,637
  • 2
  • 26
  • 43
Thuong Nguyen
  • 572
  • 2
  • 9
  • 18

2 Answers2

1
// use to delay the callback execution
// so your search will be executed only you stop typing after 0.5(500 ms for example) second
var delay = (function(){
  var timer = 0;
  return function(callback, ms){
    clearTimeout(timer);
    timer = setTimeout(function() {
      callback();
    }, ms);
  }
}());

$('#searchbox').keyup(delay(search, 500));
xdazz
  • 158,678
  • 38
  • 247
  • 274
0

You may try;

var timer = null;

$("#text_box").keyup(function() {
  if(timer) {
    clearTimeout(timer);
  }

  timer = setTimeout(search, 1000);
});

There is a similar question here that I asked before. Always do a search in stackoverflow before posting a question.

Community
  • 1
  • 1
Alfred
  • 21,058
  • 61
  • 167
  • 249