I’m trying to navigate the autocomplete dropdown using arrow keys.
JSON
{
"employees":[
{
"name": "Alex"
},
{
"name": "Alice"
},
{
"name": "Brian"
},
{
"name": "Betsy"
},
{
"name": "Beck"
},
{
"name": "Bob"
},
{
"name": "Brad"
},
{
"name": "Brown"
}
]
}
JQUERY
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<style>
.selected{background-color:pink;}
</style>
<script type="text/javascript" src="js/jquery-1.6.4.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var keyCounter = -1;
jQuery.ajax({
type: "GET",
url: "myjson.json",
dataType: "json",
async: "true",
contentType: "application/x-javascript; charset=utf-8",
cache: "false",
success: function(response){
$("input#myInput").live("keyup", function(e){
var myInputVal = $("input#myInput").val();
var myInputValLen = $("input#myInput").val().length;
$("ul#myList").empty();
for (var x = 0; x < response.employees.length; x++) {
var empName = response.employees[x].name;
if (empName.substring(0, myInputValLen).toLowerCase().search(myInputVal.substring(0, myInputValLen).toLowerCase()) != -1) {
$("ul#myList").append("<li>" + empName + "</li>");
}
}
if (e.keyCode == 40) {
var keyCnter = keyCounter;
var listLen = $("li").length;
if (keyCnter != listLen - 1) {
keyCnter++;
$("li").removeClass("selected");
$("li").eq(keyCnter).addClass("selected");
keyCounter = keyCnter;
}
}
});
}
})
})
</script>
</head>
<body>
<input type="text" width="25" id="myInput">
<ul id="myList" style="margin:0px;"></ul>
</body>
</html>
STEPS TO REPLICATE
- type in “b” in the text field. the drop down displays 6 names starting with “b”
- use down arrow key to navigate to “Betsy”
- type in “r” after “b” in the text field. the drop down displays 3 names starting with “br”
- use down arrow key to navigate. “Brown” is highlighted. Instead, “Brian” should be highlighted.
How can I reset the counter to -1?
Entirely untested, but would it make sense to just reset it to -1 if anything other than down arrow is pressed?