I have a pretty basic auto-suggestion function for my website which operates whenever a user enters something into my search input.
It is supposed to function kind of like Googles search auto-suggestion - and it sort of does. However, when some suggestions are returned, if the user hits one of the arrows on their keyboard, it will not select any suggestion.
Here is my JS (for the selection of a suggestion):
$(document).ready(function(){
var $result = $('li');
$('input').keydown(function(e){
var key = e.keyCode, $selected = $result.filter('.selected'), $current;
if(key != 40 && key != 38){
return;
}
$result.removeClass('selected');
if (key == 40){
if (!$selected.length || $selected.is(':last-child')){
$current = $result.eq(0);
} else {
$current = $selected.next();
}
} else if (key == 38){
if (!$selected.length || $selected.is(':first-child')){
$current = $result.last();
} else {
$current = $selected.prev();
}
}
$current.addClass('selected');
});
});
Here is my Ajax:
function findmatch(){
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById('s-dif').innerHTML = xmlhttp.responseText;
}
}
var qVal = document.getElementById('query-value');
xmlhttp.open('GET', 'search/suggest.php?q=' + qVal.value, true);
xmlhttp.send();
}
The very basic HTML:
<div class="form-container">
<form method="get" id="search" name="search">
<input type="text" name="q" id="query-value" onkeyup="findmatch();" placeholder="Search with Ajax...">
</form>
</div>
<div class="suggestions">
<ul id="s-dif">
</ul>
</div>
and finally, my PHP:
if(isset($_GET['q'])){
$results = '';
$query = trim($_GET['q']);
if(!empty($query)){
$stmt = $conn->prepare("SELECT title, popularity FROM autosuggest WHERE keywords LIKE :query OR title LIKE :query ORDER BY popularity desc LIMIT 7");
$query = $query . '%';
$stmt->bindParam(':query', $query);
$stmt->execute();
$count = $stmt->rowCount();
$i = 0;
if($count > 0){
while($row = $stmt->fetch(PDO::FETCH_OBJ)){
$title = $row->title;
$popularity = $row->popularity;
$i++;
$results .= '<li id="select-suggest" value="' . $i . '" name="' . $title . '">' . $title . '</li>';
}
}
}
}
print("$results");
I feel as if the problem lies within my "selection jQuery", however, I have made sure to triple check everything, but I cannot seem to find anything that would stop the feature from working.