Jquery自动完成仅在我输入第四个字母后显示结果

时间:2016-07-22 11:58:23

标签: javascript jquery autocomplete

我有一个用户插入城市名称的输入,然后我用onkeyup

调用方法
function autocompleteCity(id){


console.log($('#'+id).val());

if($('#'+id).val().length >= 2){
    var data = {
        query: $('#'+id).val()
    }

    $.ajax({
        url: location.origin + '/autocomplete/city',
        headers: {
            apiKey: APIKEY
        },
        type: "POST",
        data: data,
        dataType: "json",
        async: true,
        success: function (data) {

            var cities = [];
            for(var i=0;i<data.cities.length;i++){
                cities.push(data.cities[i].city);
            }
            console.log(cities);

            $('#'+id).autocomplete({
                source: cities
            });

        },
        error: function (err) {

            console.log(err);
        }
    });
}

}

和html

<input id="placeTo" onkeyup="autocompleteCity('placeTo')" type="text" class="form-control input-lg not-dark" value="" placeholder="Select a drop city">

例如,如果我输入“To”,我会在console.log(cities)

上输入
Array [ "Toulouse", "Toronto", "Torun", "Tours" ]

但自动填充功能未显示,直到用户输入“Toky”

这是正常的吗?或者我做错了什么?

2 个答案:

答案 0 :(得分:1)

使用指定的minLength选项初始化自动完成。

$( ".selector" ).autocomplete({ minLength: 2 });

它会起作用

答案 1 :(得分:1)

对于你的ajax,你只需要实现source选项,并且对于用户必须输入的最小字符数,有minLength选项。

$( "#city" ).autocomplete({
      source: function( request, response ) {
        $.ajax( {
          url: location.origin + '/autocomplete/city',
          dataType: "json",
          type: "POST",
          headers: {
               apiKey: APIKEY
          },  
          data: {
            q: request.term
          },
          success: function( data ) {

            // Handle 'no match' indicated by [ "" ] response
            response( data.length === 1 && data[ 0 ].length === 0 ? [] : data );
          }
        } );
      },
      minLength: 2,
      select: function( event, ui ) {
        log( "Selected: " + ui.item.label );
      }
}):