我正在实现 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; },
});
}
);
HTML 隐藏输入元素:
<div id='freeForm'>
<input name='Search Products' type='hidden' id='byProductName'>
</div>
JSON 结果:
[{"product":""},{"product":" windows"},{"product":" mac"},
{"product":" linux"},{"product":" RHEL"},{"product":"Test product list"}]
下拉列表正确填充了我的值,我可以选择多个项目并成功删除它们。但是,当我在输入字段中键入字符串以过滤结果集时,它不会进行过滤。
我尝试将数据更改为:
data: function (data, term){
return {
results: data,
query: term }
},
但是一旦我点击下拉菜单就会出现这个错误:
Uncaught TypeError: Cannot read property 'length' of undefined - select2 line 1784
如何使用查询词成功过滤结果列表?
最佳答案
来自 Select2 documentation为 data
选项:
Options [sic] for the built in query function that works with arrays.
If this element contains an array, each element in the array must contain
id
andtext
keys.Alternatively, this element can be specified as an object in which
results
key must contain the data as an array and atext
key can either be the name of the key in data items that contains text or a function that retrieves the text given a data element from the array.
这意味着您有两个选择:
(1) 更改您的
data
数组是具有 id
的对象数组和 text
在将其提供给 .select2()
之前的属性.然后你可以摆脱 id
, formatResult
和 formatSelection
选项。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
});
}
);
jsfiddle
(2) 提供对象
results
和 text
data
的属性选项。在这种情况下,您仍然需要提供 id
选项,但您可以去掉 formatResult
和 formatSelection
选项。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; }
});
}
);
jsfiddle
关于json - select2 使用查询词过滤本地 JSON 数据结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28196932/