I’ve made a search engine for my database table where the search query gets sent by Jquery AJAX to a file called search.php. Search.php then sends the result back to the Javascript file where the results are processed and added to index.php.
Everything works perfectly except when I try to add arrow key navigation. For example, I want the first item in the search results page to be selected (by appending the class, red to it and using focus()) when I press the down arrow key, the second result to be selected when I press it again, etc..
Nothing gets selected when I press either the up or down arrow key. I’m testing this in Google Chrome.
index.php:
<link rel="stylesheet" type="text/css" href="search.css">
Start searching: <input type="text" id="search" autocomplete="off">
<div id="search_results">
</div>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="search.js"></script>
javascript file:
$(document).ready(function(){
search_x = $('#search').offset().left;
search_y = $('#search').offset().top;
search_height = $('#search').height();
$('#search_results').css({
'left': search_x,
'top': (search_y + search_height + 5)
});
//arrow key navigation
start = -1;
$(document).on('keydown',document,function(e){
if(e.keyCode == 38){
if (start == -1){
start = ($('#search_results ul li a').size() - 1);
}else{
start--;
if (start < 0){
start = ($('#search_results ul li a').size() - 1);
}
}
$('#search_results ul li a').removeClass('red').focus();
$('#search_results ul li a').eq(start).addClass('red').focus();
}
if(e.keyCode == 40){
if (start == -1){
start = 0;
}else{
start++;
if (start > ($('#search_results ul li a').size() - 1)){
start = 0;
}
}
$('#search_results ul li a').removeClass('red').focus();
$('#search_results ul li a').eq(start).addClass('red').focus();
}
});
$('#search').on(
'keyup keydown',
function(){
var search_term = $(this).val();
$.post(
'search.php',
{
search_term : search_term
},function(data){
if (data == "nothing"){
$('#search_results').fadeOut();
} else {
$('#search_results').html(data).fadeIn();
}
});
});
});
part of the search.php file that sends data to index.php:
if (!empty($search_term))
{
echo '<ul>';
while ($results_row = mysql_fetch_assoc($search)){
echo '<li><a href="#">
<p><strong>',$results_row['place'],'</strong><br>',$results_row['description'],'</p>
</a>
</li>';
}
echo '</ul>';
} else {
echo "nothing";
}
After finding some free time to code again, I changed
$(document).on('keydown',document,function(e){to//stuff
});
$(document).on('keydown','#search',function(e){
//stuff
});
The key press event listener was applied to the text field,
#search. The code seemed to work after making the change.