jquery.html 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <section>
  2. <h2 id="events-public">
  3. Public jQuery events
  4. </h2>
  5. <h3>
  6. What events will Select2 trigger?
  7. </h3>
  8. {% include options/not-written.html %}
  9. <h3>
  10. How can I attach listeners for these events?
  11. </h3>
  12. {% include options/not-written.html %}
  13. <h3>
  14. What events does Select2 listen for?
  15. </h3>
  16. <p>
  17. Select2 will listen for the <code>change</code> event on the
  18. <code>&lt;select&gt;</code> that it is attached to. If you make any
  19. external changes that need to be reflected in Select2 (such as changing the
  20. value), you should trigger this event.
  21. </p>
  22. {% highlight js linenos %}
  23. $('select').val('US'); // Select the option with a value of 'US'
  24. $('select').trigger('change'); // Notify any JS components that the value changed
  25. {% endhighlight %}
  26. <h3>
  27. Can I trigger an event other than <code>change</code> to notify Select2 of changes?
  28. </h3>
  29. <p>
  30. It's common for other components to be listening to the <code>change</code>
  31. event, or for custom event handlers to be attached that may have side
  32. effects. Select2 does not have a custom event (like
  33. <code>select2:update</code>) that can be triggered other than
  34. <code>change</code>. You can rely on jQuery's event namespacing to limit
  35. the scope to Select2 though by triggering the <code>change.select2</code>
  36. event.
  37. </p>
  38. {% highlight js linenos %}
  39. $('select').val('US'); // Change the value or make some change to the internal state
  40. $('select').trigger('change.select2'); // Notify only Select2 of changes
  41. {% endhighlight %}
  42. <h3>
  43. What events can be prevented? How can I prevent a selection from being made?
  44. </h3>
  45. {% include options/not-written.html %}
  46. </section>