Skip to content

Instantly share code, notes, and snippets.

@Risto-Stevcev
Created July 31, 2015 13:00
Show Gist options
  • Save Risto-Stevcev/f1ae659432486f13a55c to your computer and use it in GitHub Desktop.
Save Risto-Stevcev/f1ae659432486f13a55c to your computer and use it in GitHub Desktop.
Javascript depdendency-free autocomplete
var items = ['Cheese, blue', 'Cheese, cheshire', 'Avocadoes, raw'];
$('.food-input').keyup(function(event) {
if (event.key.match(/^[a-zA-Z0-9, -]{1}$/g)) {
var inputVal = event.target.value;
var match = items.filter(function(item) {
return item.match(new RegExp('^'+ inputVal +'.*', 'g'));
});
if (match.length > 0) {
event.target.value = match[0];
event.target.setSelectionRange(inputVal.length, match[0].length);
}
}
});
<html>
<head>
<script type="application/javascript" src="autocomplete.js"></script>
</head>
<body>
<input class="food-input" />
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment