I have created a simple search field that will ajax in relevant search results as a user types into an input field. Everything works great, except for one thing. The input field has an onkeyup event that triggers a jQuery function that grabs the search results, which are displayed to the user in a table. The first result (row) is highlighted. I want to allow the user to use the arrow keys to navigate up and down the table of search results. However, since the input field has the onkeyup event trigger, as soon as I press the down arrow key (briefly highlighting the next table row) my onkeyup jQuery function is triggered again, re-highlighting the first search result (first row). I need a way to prevent the onkeyup function from triggering every time arrow keys are "un-pressed." Does this make sense? Am I approaching this the wrong way? Here is some of the code:
HTML:
<input id="search" type="text" onkeyup="showResult(this.value)" />
jQuery:
function showResult(str)
{
var e = str.charAt( str.length-1 )
if(e.keyCode == 38 || e.keyCode == 40)
{
$(document).keydown(function(e)
{
if (e.keyCode == 40)
{
$('tr.highlight').next("tr").addClass("highlight");
$('tr.highlight:first').removeClass("highlight");
return false;
}
else if (e.keyCode == 38)
{
$('tr.highlight').prev("tr").addClass("highlight");
$('tr.highlight:last').removeClass("highlight");
return false;
}
});
else
{
// code that gets the search results
}
You’re close, but a much simpler solution would be:
Live Example: http://jsfiddle.net/EwB6s/1/
JavaScript
HTML