Can I load data into Select2 using an array?

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.

{% highlight js linenos %} $('select').select2({ data: [ { id: 'value', text: 'Text to display' }, // ... more data objects ... ] }); {% endhighlight %}

What properties are required on the objects passed in to the array?

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.

How should nested results be formatted?

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.

{% highlight js linenos %} { text: 'Group label', children: [ { id: 'nested-1', text: 'First nested option' }, // ... more data objects ... ] } {% endhighlight %}

How many levels of nesting are allowed?

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.

Why are <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.

{% include options/not-written.html %}

My objects don't use id for their unique identifiers, what can I do?

You can re-map your identifier before passing it to Select2.

{% include options/not-written.html %}

My objects use a property other than text for the text that needs to be displayed

These can also be re-mapped.

{% include options/not-written.html %}