<html>
<head>
<script type="text/javascript" language="javascript">
var autocomplete = ['Город 1', 'Город 2', 'Город 3', 'Город 4', 'Город 5'];
window.onload = function() {
document.getElementById('input').onkeyup = keyUp;
}
function keyUp(e) {
var e = e||window.event;
switch(e.keyCode) {
case 40:
var selected = -1;
var spans = document.getElementById('autocomplete').getElementsByTagName('span');
for(i=0;i<=spans.length;i++)
if (i in spans && spans[i].className == 'selected') {
spans[i].className = '';
selected = i;
}
selected++;
for(i=0;i<=spans.length;i++)
if (i in spans && i == selected) {
spans[i].className = 'selected';
}
break;
case 38:
var spans = document.getElementById('autocomplete').getElementsByTagName('span');
var selected = spans.length;
for(i=0;i<=spans.length;i++)
if (i in spans && spans[i].className == 'selected') {
spans[i].className = '';
selected = i;
}
selected--;
for(i=0;i<=spans.length;i++)
if (i in spans && i == selected) {
spans[i].className = 'selected';
}
break;
case 13:
var spans = document.getElementById('autocomplete').getElementsByTagName('span');
for(i=0;i<=spans.length;i++)
if (i in spans && spans[i].className == 'selected') {
document.getElementById('input').value = spans[i].innerHTML;
document.getElementById('autocomplete').innerHTML = '';
}
break;
default:
var div = document.getElementById('autocomplete');
div.innerHTML = '';
if (document.getElementById('input').value.length > 0) {
autocomplete.forEach(function(elem, index) {
div.innerHTML += '<span>'+autocomplete[index]+'</span><br />';
});
}
}
}
</script>
<style>
input {
position: absolute;
top: 10px;
left: 150px;
}
#autocomplete {
position: absolute;
top: 40px;
left: 150px;
}
span.selected {
background-color: red;
}
</style>
</head>
<body>
<input type="text" id="input" />
<div id="autocomplete"></div>
</body>
</html>