使用猎犬将DOM元素的值传递给typeahead

时间:2015-07-14 15:49:55

标签: typeahead.js bootstrap-typeahead bloodhound

我想将隐藏输入字段中的值传递给bloodhound中的搜索远程URL参数。

变量是动态的,每次模态弹出窗口打开时都会更新。它的初始值为null,我相信这就是为什么它根本不起作用的原因:

url: url + 'equipment/getSuggestions/' + $('#equipment-type-input').val() + '/%QUERY',

正如您所看到的,我正在使用jQuery,但值为空。可能是因为它只是在插件初始化时才获得一次?

这里是完整的脚本:

// Instantiate the Bloodhound suggestion engine
var suggestions = new Bloodhound({
    datumTokenizer: function (datum) {
        return Bloodhound.tokenizers.whitespace(datum.value);
    },
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    remote: {
        url: url + 'equipment/getSuggestions/' + $('#equipment-type-input').val() + '/%QUERY',
        wildcard: '%QUERY',
        filter: function (movies) {
            // Map the remote source JSON array to a JavaScript object array
            return $.map(movies, function (movie) {
                return {
                    value: movie
                };
            });
        }
    }
});

// Initialize the Bloodhound suggestion engine
suggestions.initialize();

// Instantiate the Typeahead UI
$('#equipment-id-input').typeahead(null, {
    displayKey: 'value',
    source: suggestions.ttAdapter()
});

2 个答案:

答案 0 :(得分:0)

您可以将Bloodhound的远程设置为以下内容:

remote: {
  url: '/equipment/getSuggestions/%EQUIPMENT/%QUERY',
  replace: function(url) {
    return url.replace('%EQUIPMENT', $('#equipment-type-input').val()).replace('%QUERY', $('input.typeahead.tt-input').val());
  },
  filter: function (movies) {
    // Map the remote source JSON array to a JavaScript object array
    return $.map(movies, function (movie) {
      return {
        value: movie
      };
    });
  }
}

您不再需要通配符,因为您必须替换替换参数中的%QUERY。

答案 1 :(得分:0)

我最终以这种方式解决了问题:

// Instantiate the Bloodhound suggestion engine
var suggestions = new Bloodhound({
    datumTokenizer: function (datum) {
        return Bloodhound.tokenizers.whitespace(datum.value);
    },
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    remote: {
        url: url + 'equipment/getSuggestions/',
        replace: function (url, query) {
            return url + query.toUpperCase() + '/' + $('#equipment-type-input').val()
        },
        wildcard: '%QUERY',
        filter: function (numbers) {
            // Map the remote source JSON array to a JavaScript object array
            return $.map(numbers, function (number) {
                return {
                    value: number
                };
            });
        }
    }
});

// Initialize the Bloodhound suggestion engine
suggestions.initialize();

// Instantiate the Typeahead UI
$('#equipment-id-input').typeahead({
    hint: true,
    highlight: true,
    minLength: 3
}, {
    limit: 7,
    displayKey: 'value',
    source: suggestions.ttAdapter(),
});