Is it possible somehow to group results in a Select2 component when it's not using <select>
tag, but <input type="hidden">
, and results are provided as "data" option in configuration object?
var select2Options = {
data: {
results: myArrayOfResults
}
};
New options can be added to a Select2 control programmatically by creating a new Javascript Option object and appending it to the control: var data = { id: 1, text: 'Barn owl' }; var newOption = new Option(data. text, data.id, false, false); $('#mySelect2'). append(newOption).
The key here for me is to build a data array with content for both templateSelection and templateResult . The latter renders fine in the dropdown but any multiline content will not be contained in the select2 element so needs to be displayed inline (or at least on a single line).
Select2 requires that the id property is used to uniquely identify the options that are displayed in the results list. If you use a property other than id (like pk ) to uniquely identify an option, you need to map your old property to id before passing it to Select2.
Yes, the results
objects support a children
attribute...
so for example:
var select2Options = {
data: {
results: [
{text: "My shiny group", children: [
{id: 1, text: "My shiny item"},
{id: 2, text: "My shiny item2"}
]}
]
}
};
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