Skip to content

Instantly share code, notes, and snippets.

@xingmarc
Created March 20, 2017 06:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xingmarc/4063a69a0a7810297cd6e36b0d6957e2 to your computer and use it in GitHub Desktop.
Save xingmarc/4063a69a0a7810297cd6e36b0d6957e2 to your computer and use it in GitHub Desktop.
input typeahead simple example.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>A Type Ahead Example</title>
</head>
<body>
<!-- The Trick here is to use two overlapping <input>, one for the hint, one for the actual input -->
<div style="position: relative;">
<input
id="hint"
readonly
value=""
style="opacity:1; position: absolute; color: #999;"
/>
<input
id="input"
value=""
style="position: absolute; color: black; background-color: transparent;"
/>
</div>
<script>
var input = document.getElementById('input');
var hint = document.getElementById('hint');
input.onkeyup = function(e) {
// If user press right arrow => auto complete.
if (e.keyCode == 39) {
e.target.value = hint.value;
}
}
input.oninput = function(e) {
var value = e.target.value;
var hintValue = getHint(value);
hint.value = hintValue; // Change the hint value
}
function getHint(input) {
/*
This is a very simple and naive getHint function:
just return the first matched in the array.
*/
for (var i = 0; i < states.length; i++) {
if (states[i].toLowerCase().startsWith(input.toLowerCase())){
return input + states[i].slice(input.length);
}
}
return null;
}
// The data:
var states = [
'Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California',
'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii',
'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana',
'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota',
'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire',
'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota',
'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island',
'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont',
'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming'
];
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment