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).
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:
It is possible to extend the <OPTION>
elements representing selection with the HTML data-* attributes containing arbitrary data from the source data objects:
In addition, properties/values from source data objects can ba accessed from within an event handler:
{% highlight js linenos %} $('select').on('select2:select', function (event) { console.log(event.params.data) }); {% endhighlight %}