Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search/filter for an array

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 {
        }
    }
like image 466
Some Name Avatar asked Jan 03 '23 22:01

Some Name


1 Answers

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>
like image 87
madebydavid Avatar answered Jan 06 '23 12:01

madebydavid