How to programmatically access a selection data?

There are few ways to programmatically access the selection data. Calling select2('data') will return the JavaScript array of an objects representing the current selection. Each object will have properties/values which was in the source data objects passed through processResults and templateResult functions (as in Loading data from an array and Connecting to a remote data source).

{% highlight js linenos %} $('select').select2('data'); {% endhighlight %}

As Select2 uses the HTML <SELECT> element to store the selection result, the selection data are represented by <OPTION> elements and can be accessed in the plain jQuery/DOM manner. The resulting elements will have properties/values from the source data objects, stored by the means of jQuery data() method and accessible by key 'data':

{% highlight js linenos %} // Retrieve source data object's data of the first selected element $('select').find(':selected').data('data'); {% endhighlight %}

Another technique is not to rely on jQuery's data() method but to extend the <OPTION> elements representing selection with the HTML data-* attributes containing arbitrary data from the source data objects:

{% highlight js linenos %} $('select').select2({ // ... templateSelection: function (data, container) { $(data.element).attr('data-custom-attribute', data.customValue); return data.text; } }); // Retrieve custom attribute value of the first selected element $('select').find(':selected').attr('data-custom-attribute') {% endhighlight %}

In addition, properties/values from source data objects can ba accessed from within event handler:

{% highlight js linenos %} $('select').on('select2:select', function (event) { console.log(event.params.data) }); {% endhighlight %}