twitter-bootstrap - Bootstrap 3 typeahead.js - 通过 typeahead val 的一部分进行查询

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

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

and when dropdown item selected,

enter image description here

将新值添加到行尾

enter image description here

知道如何使它工作吗?

最佳答案

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

);

关于twitter-bootstrap - Bootstrap 3 typeahead.js - 通过 typeahead val 的一部分进行查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18323650/

相关文章:

javascript - 未设置 Bootstrap Datepicker 属性

javascript - 如何使用 Modal Bootstrap 确认删除是/否?

javascript - 预先输入不建议任何内容

twitter-bootstrap - Twitter Bootstrap : Typeahead function for no matches

html - 删除大屏幕上封面图像和粘性页脚之间的白色间距

php - Bootstrap 移动菜单不显示在 wordpress 中

html - div 内的标题用作覆盖。我怎样才能使文本居中?

visual-studio-2013 - Visual Studio 上的 SASS Web Essentials 编译器全局变量

jquery - 使用引导工具提示在悬停时显示 XML 标签

javascript - Angular UI typeahead 下拉菜单不出现