You could do this
Add the keyDown callback to the input (I assume it is an HTMLInputElement
)
In the keyDown callback delay the call to searchNameFromInput
function so that the value of the input has already change when you check it.
Filter elements in nameArray
by creating a regex that checks for matches of names with your input value from the beginning (for instance: "an"
would match "anivia"
and "annie"
)
The code looks like this
var nameArray = ["aatrox","ahri","akali","alistar","amumu","anivia","annie","ashe", "blitzcrank", "brand", "caitlyn", "cassiopeia", "cho'gath", "corki", "darius", "diana", "draven", "dr. mundo", "elise", "evelynn", "ezreal", "fiddlesticks", "fiora", "fizz", "galio", "gangplank", "garen", "gragas", "graves", "hecarim", "heimerdinger", "irelia", "janna", "jarvan iv", "jax", "jayce", "karma", "karthus", "kassadin", "katarina", "kayle", "kennen", "kha'zix", "kog'maw", "leblanc", "lee sin", "leona", "lissandra", "lucian", "lulu", "lux", "malphite", "malzahar", "maokai", "master yi", "m.fortune", "mordekaiser", "morgana", "nami", "nasus", "nautilus", "nidalee", "nocturne", "nunu", "olaf", "orianna", "pantheon", "poppy", "quinn", "rammus", "renekton", "rengar", "riven", "rumble", "ryze", "sejuani", "shaco", "shen", "shyvana", "singed", "sion", "sivir", "skarner", "sona", "soraka", "swain", "syndra", "talon", "taric", "teemo", "thresh", "tristana", "trundle", "tryndamere", "twitch", "twisted fate", "udyr", "urgot", "varus", "vayne", "veigar", "vi", "viktor", "vladimir", "volibear", "warwick", "wukong", "xerath", "xin zhao", "yorick", "zac", "zed", "ziggs", "zilean", "zyra", "jinx"],
input = document.getElementById('foo');
// I also assume IE9+ for addEventListener
input.addEventListener('keydown', function keyDown(e) {
e = e || window.event;
// just bind the input element as a parameter
// for the function searchNameFromInput
setTimeout(searchNameFromInput.bind(null, e.target||e.srcElement), 80);
}, false);
function searchNameFromInput(input) {
if (input.value.length) {
console.log(
nameArray.filter(function (name) {
return new RegExp('^' + input.value).test(name);
})
);
}
}