selection-access.html 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  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. The resulting elements will have properties/values from the source data objects, stored by the means of jQuery <code>data()</code> method and accessible by key <code>'data'</code>:
  13. </p>
  14. {% highlight js linenos %}
  15. // Retrieve source data object's data of the first selected element
  16. $('select').find(':selected').data('data');
  17. {% endhighlight %}
  18. <p>
  19. Another technique is not to rely on jQuery's <code>data()</code> method but to extend the <code>&lt;OPTION&gt;</code> elements representing selection with the HTML data-* attributes containing arbitrary data from the source data objects:
  20. </p>
  21. {% highlight js linenos %}
  22. $('select').select2({
  23. // ...
  24. templateSelection: function (data, container) {
  25. $(data.element).attr('data-custom-attribute', data.customValue);
  26. return data.text;
  27. }
  28. });
  29. // Retrieve custom attribute value of the first selected element
  30. $('select').find(':selected').attr('data-custom-attribute')
  31. {% endhighlight %}
  32. </section>