I am implementing select2 version 3.5.0. I am using the following jQuery inside my document ready function:
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 hidden input element:
<div id='freeForm'>
<input name='Search Products' type='hidden' id='byProductName'>
</div>
JSON result:
[{"product":""},{"product":" windows"},{"product":" mac"},
{"product":" linux"},{"product":" RHEL"},{"product":"Test product list"}]
The drop down populates my values correctly and I can select multiple items and remove them successfully. However, when I type a string in the input field to filter the result set, it does not filter.
I have tried altering data: to the following:
data: function (data, term){
return {
results: data,
query: term }
},
but get this error once I click the drop down:
Uncaught TypeError: Cannot read property 'length' of undefined - select2 line 1784
How do I filter the result list successfully with a query term?
From the Select2 documentation for the data
option:
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.
This means you have two options:
(1) Alter your data
array to be an array of objects with id
and text
properties before giving it to .select2()
. You can then get rid of the id
, formatResult
and formatSelection
options.
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) Supply an object with results
and text
properties for the data
option. In this case, you still need to supply the id
option, but you can get rid of the formatResult
and formatSelection
options.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With