【问题标题】:Bootstrap 3 typeahead.js - query by part of typeahead valBootstrap 3 typeahead.js - 通过 typeahead val 的一部分进行查询
【发布时间】:2013-08-21 19:57:03
【问题描述】:

我正在尝试使用输入值的最后一部分调用我的远程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
});

以及选择下拉项,

在行尾添加新值

知道如何实现吗?

【问题讨论】:

  • 您可能需要考虑,您还需要首先获取输入中的所有逗号分隔值,并将它们从结果数据集中删除。在使用最后一个输入值显示建议列表之前,除非您的规划允许重复。您还必须禁用自动完成/提示?由于我猜这会影响您的输入。 span>

标签: twitter-bootstrap twitter-bootstrap-3 bootstrap-typeahead typeahead typeahead.js


【解决方案1】:

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

您将不得不覆盖updater 和matcher 函数。对于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: replace last occurrence of text in a string)

完整示例:

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

);

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-20
      • 1970-01-01
      • 2015-11-30
      • 1970-01-01
      相关资源
      最近更新 更多