Reputation: 571
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 {
}
}
Upvotes: 4
Views: 1905
Reputation: 6527
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>
Upvotes: 5
Reputation: 42054
Using jQuery UI autocomplete this task can be done very easily:
$('#ingredient').autocomplete({
source: ["Appel", "Aardbei", "Aardappelen", "Banaan", "Bananen", "Banana"]
});
<link href="https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>
<input id="ingredient">
Upvotes: 4
Reputation: 22445
Going under the instructions, you can use a regular expression filter here on your array.
const results = ingredienten.filter(item => item.match(/^ban/)); //add i at the end to ignore case
This will iterate the array and return all the results that match the regex "starts with 'ban'".
You can also do a 0-2 substring match == 'ban' but that's a bit more manual.
Upvotes: 1