Reputation: 754
Hi i have the following auto-suggestion box set up and i want to select the outputs with keyboard and mouse. how can i do that?
Javascript code:
function showResult(string) {
if (string.lenght==0) {
document.getElementById("livesearch").innerHTML="";
document.getElementById("livesearch").style.border="0px";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {
//code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
}
document.getElementById("livesearch").innerHTML = xmlhttp.responseText;
document.getElementById("livesearch").style.border = "1px solid #A5ACB2";
}
xmlhttp.open("GET","test.php?q=" + string,true);
xmlhttp.send();
}
PHP code:
$xmlDoc=new DOMDocument();
//$xmlDoc->load("test.xml");
$xml = simplexml_load_file("test.xml");
//$x=$xmlDoc->getElementsByTagName('datas');
//get the q parameter from URL
$q = $_GET["q"];
if (strlen($q) > 0) {
foreach ($xml->datas as $a) {
$var = $a->attributes();
$domain = stristr($var,$q);
echo $domain."\n";
echo "<br/>";
}
if (strlen($domain) == 0) {
echo "no results";
}
Everything works fine at this point. But I don't know how to interact with the list.
Upvotes: 1
Views: 1487
Reputation: 2086
It would be better to user some proper autocomplete jQuery. You can search by "autocomplete jquery" and find out a jQuery which fits your requirements. If you want to write your own code then you can make functions which work for mouse and keyboard events:
txtSearchBox.keyup(function (e) {
// get keyCode (window.event is for IE)
var keyCode = e.keyCode || window.event.keyCode;
var lastSearch = txtSearchBox.val();
// check for an ENTER
if (keyCode == 13) {
OnEnterClick();
return;
}
// check an treat up and down arrows
if (OnUpDownClick(keyCode)) {
return;
}
// check for an ESC
if (keyCode == 27) {
clearResults();
return;
}
});
And then in "OnEnterClick()", "OnUpDownClick()" and "OnUpDownClick()" you can display what you want like:
function OnUpDownClick(keyCode) {
if(keyCode == 40 || keyCode == 38){
if(keyCode == 38){ // keyUp
// Do something keyUp event
} else { // keyDown
// Do something for keyDown event
}
return true;
} else {
// reset
return false;
}
}
Upvotes: 1