Reputation: 47
This code is about Autocomplete with an external JSON array. My problem is that the autocomplete only displays when I entered the first two initial words. For example, I want to find the capital "Kabul", I have to enter "Ka" to find the capital in the autocomplete. If I enter "ab" or " bu", it won't show "Kabul". Please help me.
$(function() {
$("#answer").autocomplete({
minLength: 2,
source: function(request, response) {
var display = [];
$.each(array, function(k, v) {
if (v.capital.toLowerCase().indexOf(request.term.toLowerCase()) == 0) {
display.push({ "label": v.capital });
return;
}
});
response(display);
},
Upvotes: 1
Views: 86
Reputation: 337580
The issue is because indexOf
will return the zero-based index of the occurrence of the string you're looking for, or -1
if it's not found. Therefore your use of == 0
in the if
condition will only hit when the search string is found at the start of the source.
To amend this behaviour change the condition to !== -1
,:
if (v.capital.toLowerCase().indexOf(request.term.toLowerCase()) !== 1) {
Upvotes: 1