While Select2 is designed to be used with a <select>
tag
the data that is used to search through and display the results can be
loaded from a JavaScript array using the data
option. This
option should be passed in during the initialization of Select2.
The id
and text
properties are required on each
object, and these are the properties that Select2 uses for the internal
data objects. Any additional paramters passed in with data objects will be
included on the data objects that Select2 exposes.
id
properties have to be strings?
Because the value
attributes on a <select>
tag must be strings, the id
property on the data objects must
also be strings. Select2 will attempt to convert anything that is not a
string to a string, which will work for most situations, but it is
recommended to force all of your ids to strings ahead of time.
0
!
See Do the id
properties have to be strings?.
Nested results should be specified using the children
property
on the data objects that are passed in. This children
property
should be an array of data objects that are grouped under this option, and
the label for the group should be specified as the text
property on the root data object.
Because Select2 falls back to an <optgroup>
when
creating nested options, only
a single level of nesting
is supported. Any additional levels of nesting is not guarenteed to be
displayed properly across all browsers and devices.
<option>
tags being created?
The data
option is a shortcut that Select2 provides which
allows you to load options into your select
from a data array.
id
for their unique identifiers,
what can I do?
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.
If you cannot do this on your server or you are in a situation where the identifier cannot be changed, you can do this in JavaScript before passing it to Select2.
{% highlight js linenos %} var data = $.map(yourArrayData, function (obj) { obj.id = obj.id || obj.pk; // replace pk with your identifier return obj; }); {% endhighlight %}text
for the text that
needs to be displayed
Just like with the id
property, Select2 requires that the text
that should be displayed for an option is stored in the text
property. You can map this property from any existing property using the
following JavaScript.