templating.html 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. <section>
  2. <h2 id="templateSelection">
  3. How can I customize the way selections are displayed?
  4. </h2>
  5. <p>
  6. When a selection is made by the user Select2 will display the text of the option by default, just like how it is displayed in a standard select box. You can override the display of the selection by setting the <code>templateSelection</code> option to a JavaScript function.
  7. </p>
  8. {% highlight js linenos %}
  9. function template(data, container) {
  10. return data.text;
  11. }
  12. $('select').select2({
  13. templateSelection: template
  14. });
  15. {% endhighlight %}
  16. <h3>
  17. Nothing is being displayed when I select an option
  18. </h3>
  19. {% include options/not-written.html %}
  20. <h3>
  21. I am using HTML in my selection template but it isn't displaying it
  22. </h3>
  23. <p>
  24. If you want to use HTML in your selection template, you will need to return a jQuery object. Otherwise, Select2 will assume that your template only returns text and will escape it.
  25. </p>
  26. {% highlight js linenos %}
  27. function template(data, container) {
  28. return $('<strong></strong>')
  29. .text(data.text);
  30. }
  31. $('select').select2({
  32. templateSelection: template
  33. });
  34. {% endhighlight %}
  35. <h3>
  36. How can I access the container where the selection is displayed?
  37. </h3>
  38. {% include options/not-written.html %}
  39. </section>