Input Autocomplete by Placeholder

by Akhmedov Khumoyun

HTML

<div class="example-words">
  <p>Enter one of  these words: 
   Preclude, Predator_1, Semantic_RL, Thorn, Kill_09, One
  </p>
</div>

<div id="autocomplete-container">
  <div id="autocomplete"></div>
  <input
    id="main-input" 
    type="text"
    placeholder="Enter route..." /> 
</div>

<div class="info">
  Press `Enter` or `RightArrow` to autocomplete the word
</div>

CSS

body {
 background-color: #ebfbff;
}

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;
  background-color: white;
}

#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;
}


.example-words, .info {
  text-align: center;
  font: 13px "Palatino Linotype", "Book Antiqua", Palatino, serif;
}

.example-words {
  width: 60%;
  margin: 0 auto;
  margin-top: 50px;
  color: #05074d;
  font-size: 18px;
}

.info {
  width: 350px;
  background-color: #339;
  color: yellow;
  margin: 20px auto;
  padding: 5px;
  border-radius: 5px;
}

JavaScript

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) {
	// e.preventDefault();
	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;
}