Bootstrap 3 typeahead.js - 按类型的部分查询

Dan*_*kin 9 typeahead twitter-bootstrap bootstrap-typeahead typeahead.js twitter-bootstrap-3

我正在尝试使用输入值的最后一部分调用我的远程URL.我想做这样的事情:

    $('#typeahead').typeahead({
    remote: {
        url: '/ajax/tags/get/?name=%QUERY',
        replace: function (url, query) {
            var last = query.split(',');
            last = $.trim(last[last.length-1]);
            return url.replace('%QUERY', last);
        }
    },
    limit : 10
});
Run Code Online (Sandbox Code Playgroud)

当选择下拉项时,

在此输入图像描述

将新值添加到行尾

在此输入图像描述

知道如何做到这一点吗?

Bas*_*sen 1

对于 Bootstrap 3,您可以使用Bootstrap-3-Typeahead

您将必须覆盖updatermatcher函数。对于该matcher函数,您可以使用替换函数中的代码,如下所示:

matcher: function (item) {
        var last = this.query.split(',');
        this.query = $.trim(last[last.length-1]);

        if(this.query.length) return ~item.toLowerCase().indexOf(this.query.toLowerCase());
}
Run Code Online (Sandbox Code Playgroud)

将以下代码用于您的update

updater: function (item) {
      return this.$element.val().replace(new RegExp(this.query + '$'),'') + item + ',';
    }
Run Code Online (Sandbox Code Playgroud)

(匹配最后一次出现的位置:JavaScript:替换字符串中最后一次出现的文本

完整示例:

$('.typeahead').typeahead (
{
items: 4,
source: function (query, process) {
    states = [];
    map = {};


    var data = [
        {"stateCode": "CA", "stateName": "California"},
        {"stateCode": "AZ", "stateName": "Arizona"},
        {"stateCode": "NY", "stateName": "New York"},
        {"stateCode": "NV", "stateName": "Nevada"},
        {"stateCode": "OH", "stateName": "Ohio"}
    ];

    $.each(data, function (i, state) {
        map[state.stateName] = state;
        states.push(state.stateName);
    });

    process(states);

}

  , updater: function (item) {
      return this.$element.val().replace(new RegExp(this.query + '$'),'') + item + ',';
    }
    , matcher: function (item) {
        var last = this.query.split(',');
        this.query = $.trim(last[last.length-1]);

        if(this.query.length) return ~item.toLowerCase().indexOf(this.query.toLowerCase());
    }
    }

);
Run Code Online (Sandbox Code Playgroud)