selection-access.html 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. <section>
  2. <h2 id="selection-api-access">
  3. How to programmatically access a selection data?
  4. </h2>
  5. <p>
  6. There are few ways to programmatically access the selection data. Calling <code>select2('data')</code> 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 <code>processResults</code> and <code>templateResult</code> functions (as in <a href="#data">Loading data from an array</a> and <a href="#ajax">Connecting to a remote data source</a>).
  7. </p>
  8. {% highlight js linenos %}
  9. $('select').select2('data');
  10. {% endhighlight %}
  11. <p>
  12. As Select2 uses the HTML <code>&lt;SELECT&gt;</code> element to store the selection result, the selection data are represented by <code>&lt;OPTION&gt;</code> elements and can be accessed in the plain jQuery/DOM manner:
  13. </p>
  14. {% highlight js linenos %}
  15. $('select').find(':selected');
  16. {% endhighlight %}
  17. <p>
  18. It is possible to extend the <code>&lt;OPTION&gt;</code> elements representing selection with the HTML data-* attributes containing arbitrary data from the source data objects:
  19. </p>
  20. {% highlight js linenos %}
  21. $('select').select2({
  22. // ...
  23. templateSelection: function (data, container) {
  24. $(data.element).attr('data-custom-attribute', data.customValue);
  25. return data.text;
  26. }
  27. });
  28. // Retrieve custom attribute value of the first selected element
  29. $('select').find(':selected').attr('data-custom-attribute')
  30. {% endhighlight %}
  31. <p>
  32. In addition, properties/values from source data objects can ba accessed from within an event handler:
  33. </p>
  34. {% highlight js linenos %}
  35. $('select').on('select2:select', function (event) {
  36. console.log(event.params.data)
  37. });
  38. {% endhighlight %}
  39. </section>