select2 使用查询词过滤本地 JSON 数据结果

mic*_*ury 5 json local filter jquery-select2

我正在实施 select2 版本 3.5.0。我在我的文档就绪函数中使用了以下 jQuery:

jQuery.getJSON('/rest/call/to/retrieve/JSON').done(
  function( data ) {
     jQuery('#byProductName').select2({
         placeholder: 'Type any portion of a single product name...',
         allowClear: true,
         minimumInputLength: 0,
         multiple: true,
         id: function(data){ return data.product; },
         data: data,
         formatResult: function(data){ return data.product; },
         formatSelection: function(data){ return data.product; },
     });
  }
);
Run Code Online (Sandbox Code Playgroud)

HTML 隐藏输入元素:

<div id='freeForm'>
    <input name='Search Products' type='hidden' id='byProductName'>
</div>
Run Code Online (Sandbox Code Playgroud)

JSON 结果:

[{"product":""},{"product":" windows"},{"product":" mac"},
 {"product":" linux"},{"product":" RHEL"},{"product":"Test product list"}]
Run Code Online (Sandbox Code Playgroud)

下拉列表正确填充了我的值,我可以选择多个项目并成功删除它们。但是,当我在输入字段中键入字符串以过滤结果集时,它不会进行过滤。

我尝试将数据更改为:

data: function (data, term){
    return { 
        results: data,
        query: term }
    },
Run Code Online (Sandbox Code Playgroud)

但是一旦我点击下拉菜单就会出现这个错误:

Uncaught TypeError: Cannot read property 'length' of undefined - select2 line 1784
Run Code Online (Sandbox Code Playgroud)

如何使用查询词成功过滤结果列表?

Joh*_*n S 4

来自该选项的Select2 文档data

与数组一起使用的内置查询函数的选项[原文如此]。

如果该元素包含一个数组,则数组中的每个元素都必须包含idtext键。

或者,可以将此元素指定为一个对象,其中 results键必须包含数组形式的数据,并且text键可以是包含文本的数据项中键的名称,也可以是从给定数据元素中检索文本的函数。大批。

这意味着您有两个选择:

(1) 将数组更改为具有和属性data的对象数组,然后再将其赋予。然后您可以去掉,和选项。idtext.select2()idformatResultformatSelection

jQuery.getJSON('/rest/call/to/retrieve/JSON').done(
    function( data ) {

        data = $.map(data, function(item) {
            return { id: item.product, text: item.product }; 
        });

        jQuery('#byProductName').select2({
            placeholder: 'Type any portion of a single product name...',
            allowClear: true,
            minimumInputLength: 0,
            multiple: true,
            data: data
        });
    }
);
Run Code Online (Sandbox Code Playgroud)

jsfiddle

(2) 提供一个带有results选项text属性的对象data。在这种情况下,您仍然需要提供该id选项,但您可以去掉formatResultformatSelection选项。

jQuery.getJSON('/rest/call/to/retrieve/JSON').done(
    function( data ) {
        jQuery('#byProductName').select2({
            placeholder: 'Type any portion of a single product name...',
            allowClear: true,
            minimumInputLength: 0,
            multiple: true,
            data: { results: data, text: 'product' },
            id: function(item) { return item.product; }
        });
    }
);
Run Code Online (Sandbox Code Playgroud)

jsfiddle