Bootstrap 3 typeahead.js - 按部分typeahead值查询

10
我想调用远程URL,其中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
});

当下拉项被选中时,将新值添加到行末

enter image description here

有什么办法可以让它工作?


你可能需要考虑到,在使用最后一个输入值来显示建议列表之前,你还需要先获取输入中所有逗号分隔的值并将它们从结果数据集中删除,除非你打算允许重复。此外,你可能还需要禁用自动完成/提示功能,因为我猜这会影响你的输入。 - Pricey
2个回答

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

使用以下代码进行您的更新:update

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

(匹配最后一次出现的位置: 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());
    }
    }

);

0
假设“使用最后一部分查询”对您有效,您可以使用filter: function(response) {...}来填充并返回一个数据数组,该数组具有适当的valuetitle以执行您想要的操作。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接