Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autocomplete function with underscore/JS

what is the proper way to implement an autocomplete search with undescore?

i have a simple array (cities) and a text input field ($.autocomplete). when the user enters the first letters in the auto-complete textfield, it should output an array with all the cities starting with the entered letters (term).

cities:

["Graz","Hamburg","Innsbruck","Linz","München","Other","Salzburg","Wien"]

eventlistener:

$.autocomplete.addEventListener("change", function(e){
  var cities = cities_array;
  var term = $.autocomplete.value;
  var results = _.filter(cities, function (city){

    return 

});
console.log(results +  "this is results");
});

I’ve tried it with _.contains, but it only returns the city when its a complete match (e.g Graz is only output when „Graz“ is entered but not when „Gr“ is entered).

the _.filter/._select collection at http://underscorejs.org/docs/underscore.html are not very clear for me and the closest i found here is filtering JSON using underscore.

but i don’t understand the indexOf part.

thx for any suggestions!

like image 403
user24957 Avatar asked May 01 '26 08:05

user24957


1 Answers

By using #filter and #indexOf, you can get quite close to a pretty decent autocomplete.

What #indexOf does is that it checks the string if it contains the inputVal. If it does not contain it it'll return -1 therefore our predicate below will work without fail.

Another small trick here is that you (read I) wanted it to be possible to search for s and get a hit for Innsbruck and Salzburg alike therefore I threw in #toLowerCase so that you always search in lower case.

return _.filter(cities, function(city) {
    return city.toLowerCase().indexOf(inputVal.toLowerCase()) >= 0;
});
like image 189
Henrik Andersson Avatar answered May 05 '26 06:05

Henrik Andersson