简体   繁体   中英

Autocomplete is matching word starting only

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);
    },

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) {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM