As cruxst suggests, there are plugins for this kind of thing, but maybe you don't want to use a plugin. Perhaps you are trying to figure it out for yourself.
Here is a piece of code that implements a very simple autocomplete. It's not a plugin and it's pretty basic but it has the basic features.
Your question suggests that the function that you may be interested in is highlightResult
.
Below the script is the markup and style required.
$(function() {
// OPTIONS
// length of time, in milliseconds, to wait after a keystroke before the search happens
// usually 250 ~ 400ms
var wait = 250;
// the minimum number of characters required to search on
var minChars = 3;
var queryScript = 'inc/ajax_search.php';
// cache our two main players for efficiency
var $input = $('#searchinput');
var $output = $('#searchresults' );
// to store the timeout
var delay = null;
$input.keypress( function( e ) {
switch( e.keyCode ) {
case 13: // return
e.preventDefault();
selectResult();
return;
case 38: // up
e.preventDefault();
highlightResult( -1 );
return;
case 40: // down
e.preventDefault();
highlightResult( 1 );
return;
//case ... there may be keys that you want to ignore like left and right
}
clearTimeout( delay );
delay = setTimeout( search, wait );
});
function search() {
var query = $.trim( $input.val() );
if( query && query.length >= minChars ) {
$output.load( queryScript, { searchinput: query } );
}
}
function highlightResult( n ) {
if( Math.abs(n) != 1 ) return;
var hilgt = $output.find( '.highlight' );
var newhilgt;
// if we don't have a highlighted element...
if( !hilgt.length ) {
if( n > 0 ) {
// highlight the first one
$output.find('li').eq(0).addClass('highlight');
// jq 1.4+
//$output.find('li').first().addClass('highlight');
} else {
// highlight the last one
$output.find('li').slice( -1 ).addClass('highlight');
// jq 1.4+
//$output.find('li').last().addClass('highlight');
}
}
if( n > 0 ) {
var newhilgt = hilgt.next();
} else {
var newhilgt = hilgt.prev();
}
if( newhilgt.length ) {
newhilgt.addClass('highlight');
hilgt.removeClass('highlight');
}
}
function selectResult() {
var sel = $output.find( '.highlight' );
if( sel.length ) {
// do something with the selected element
console.log( sel[0] );
}
}
// For completeness the functions below handle mouse stuff
$('#searchresults li').live( 'mouseover', function( e ) {
$(this).siblings('.highlight').removeClass('highlight');
$(this).addClass('highlight');
});
$('#searchresults li').live( 'click', function( e ) {
e.preventDefault();
selectResult();
})
});
Requirements
<style type="text/css">
.highlight {
background: red;
}
</style>
<input type="text" id="searchinput"/>
<div id="searchresults"></div>
Return from your ajax call assumed to be something like
<ul>
<li>result 1</li>
<li>result 2</li>
<li>result 3</li>
...
</ul>