I attempting to write a simple JQuery search.
This is what I have so far:
$(document).ready(function(){
$("#search").bind("keydown", function() {
if($("#search").val() != ''){
$.get("/search", {phrase: $("#search").val()}, function(data) {
$("#searchResults").html(data);
});
}else{
$("#searchResults").html('');
}
});
});
The problem I am having is that when I press down a key the first letter is not sent to the server. In addition, I have to hit backspace twice before the searchResults are cleared.
I have been using Firefox to observer the get requests.
For example, I press the key “f” and the phrase value passed via the get request is blank. If I press “ff” then only “f” is sent via the get request. I have to press backspace twice before the searchResults are cleared.
Does anyone know what the problem is or how I can change this to avoid this problem?
Thank you,
Brian
Bind to the
keyupevent instead. You’re sending the request before the current keystroke has been added to the value. The event order of key presses iskeydown,keypress,keyup, and the value is updated between the press and up events.