I am making a search function for an array. I have a input[text] where for example I put 'ban', then I need all results that start with 'ban' to show up, for example banana, banana milkshake, banana(fried), etc.
How would I go about doing this? I tried, but every time I try it isn't accurate. What I tried is below.
What I have:
var inputBox = document.getElementById('ingredient');
var ingredienten = ["Appel", "Aardbei", "Aardappelen", "Banaan", "Bananen", "Banana"]
inputBox.onkeydown = function(evt) {
$("#autocomplete").empty();
// INSERT CODE FOR SEARCH FUNCTION
}
I had one that came very close, however when I typed 'ban' it came up with 'Aardbei'. Which is obviously wrong. Here it is, maybe I overlooked something?
var inputBox = document.getElementById('ingredient');
var ingredienten = ["banaan", "bananen", "baan", "banana", "baaanana"];
inputBox.onkeydown = function(evt) {
$("#autocomplete").empty();
var input, filter, a, i;
input = document.getElementById("myInput");
filter = inputBox.value.toUpperCase();
for (i = 0; i < ingredienten.length; i++) {
a = ingredienten[i];
if (a.toUpperCase().indexOf(filter) > -1) {
//console.log(a);
$("#autocomplete").append("<li>" + a + "</li>");
} else {
}
}
I think you should use the keyup
event instead and you can make use of a regex and the filter
function on the array of items:
var inputBox = document.getElementById('ingredient');
var ingredienten = ["Appel", "Aardbei", "Aardappelen", "Banaan", "Bananen", "Banana"]
inputBox.onkeyup = function(evt) {
$("#autocomplete").empty();
var query = $('#ingredient').val();
// escape regex
query = query.replace(
/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"
);
var queryRegExp = new RegExp('^' + query, 'i');
var results = ingredienten.filter(function(item) {
return queryRegExp.test(item);
});
results.forEach(function(item) {
$("#autocomplete").append("<li>" + item + "</li>");
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="ingredient" />
<div id="autocomplete"></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With