const names = [
'Predator_1', 'Semantic_RL', 'Thorn', 'Kill_09', 'One', 'Preclude'
];
const container = document.querySelector('#autocomplete-container');
const autocomplete = container.querySelector('#autocomplete');
const mainInput = container.querySelector('#main-input');
mainInput.addEventListener('keyup', onKeyUp, false);
let foundName = '';
function onKeyUp(e) {
console.log( mainInput.value, e );
console.log( autocomplete.textContent );
if (mainInput.value === '') {
autocomplete.textContent = '';
return;
}
if (keyChecker(e, 'Enter') || keyChecker(e, 'ArrowRight') ) {
console.log('keyChecker')
mainInput.value = foundName;
autocomplete.textContent = '';
}
let found=false;
for (let word of names) {
if (word.indexOf(mainInput.value) === 0) {
foundName = word;
autocomplete.textContent = word;
break;
} else {
foundName = '';
autocomplete.textContent = '';
}
}
}
function keyChecker(e, key) {
const keys = {
'ArrowRight':37,
'Enter':13,
'ArrowLeft':39
}
if (e.keyCode === keys[key] || e.which === keys[key] || e.key === key) return true;
return false;
}
div#autocomplete-container, input#main-input {
font: 14px Tahoma, Verdana, Arial, sans-serif;
}
#autocomplete-container {
position: relative;
box-sizing: border-box;
width: 300px;
height: 32px;
line-height: 32px;
margin: 0 auto;
}
#autocomplete {
width: 300px;
position: absolute;
top: 0;
left: 0;
padding: 0 8px;
line-height: 32px;
box-sizing: border-box;
height: 32px;
color: #999;
cursor: text;
}
#autocomplete-container input[type=text] {
position: absolute;
top: 0;
left: 0;
width: 300px;
height: 32px;
line-height: 32px;
border: 1px solid #aaa;
border-radius: 4px;
outline: none;
padding: 0 8px;
box-sizing: border-box;
transition: 0.2s;
background-color: transparent;
cursor: text;
}
#autocomplete-container input[type=text]:focus {
border-color: dodgerBlue;
box-shadow: 0 0 8px 0 dodgerBlue;
}
<div id="autocomplete-container">
<div id="autocomplete"></div>
<input
id="main-input"
type="text"
placeholder="Enter route..." />
</div>