Skip to content

Instantly share code, notes, and snippets.

@SarahBourgeois
Created May 31, 2017 09:05
Show Gist options
  • Save SarahBourgeois/0fb8f6a22fe48ee6a180555e7d4d3940 to your computer and use it in GitHub Desktop.
Save SarahBourgeois/0fb8f6a22fe48ee6a180555e7d4d3940 to your computer and use it in GitHub Desktop.
Simple autocompletion without lib - Javascript
// you're not force to use an array.
var country = ["Finlande", "Fidji", "France", "Espagne", "Equateur", "Etipie", "Estuanie", "Albania","Algeria","Andorra","Angola","Antigua","Armenia", "France", "Bali"]
// search match
function searchCountry(input) {
var reg = new RegExp(input.split('').join('\\w*').replace(/\W/, ""), 'i');
return country.filter(function(nameOfCountry) {
if (nameOfCountry.match(reg)) {
return nameOfCountry;
}
});
}
// display words matched (called in the html file)
function displayMatch(inputText) {
var autoComplete= searchCountry(inputText);
document.getElementById("result").innerHTML = autoComplete;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Simple autocompletion</title>
</head>
<body>
<input type="text" onkeyup="displayMatch(this.value)">
<div id="result"></div>
<script src="autocompletion.js" type="text/javascript"></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment