data-attributes.html 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <section>
  2. <h2 id="data-attributes">
  3. Can I declare my configuration within the HTML?
  4. </h2>
  5. <p>
  6. It is recommended that you declare your configuration options for Select2
  7. when initializing Select2. You can also define your configuration options
  8. by using the HTML5 <code>data-*</code> attributes, which will override
  9. any options set when initializing Select2 and any defaults.
  10. </p>
  11. <h3>
  12. How should <code>camelCase</code> options be written?
  13. </h3>
  14. <p>
  15. This means that if you declare your <code>&lt;select&gt;</code> tag as...
  16. </p>
  17. <pre class="prettyprint">
  18. &lt;select data-tags="true" data-placeholder="Select an option"&gt;&lt;/select&gt;
  19. </pre>
  20. <p>
  21. Will be interpreted the same as initializing Select2 as...
  22. </p>
  23. <pre class="prettyprint linenums">
  24. $("select").select2({
  25. tags: "true",
  26. placeholder: "Select an option"
  27. });
  28. </pre>
  29. <h3>
  30. Are options with nested configurations supported?
  31. </h3>
  32. <p>
  33. You can also define nested configurations, which are typically needed for
  34. options such as AJAX. Each level of nesting should be separated by two
  35. dashes (<code>--</code>) instead of one. Due to
  36. <a href="https://github.com/jquery/jquery/issues/2070">a jQuery bug</a>,
  37. nested options using <code>data-*</code> attributes
  38. <a href="https://github.com/select2/select2/issues/2969">do not work in jQuery 1.x</a>.
  39. </p>
  40. <pre class="prettyprint">
  41. &lt;select data-ajax--url="http://example.org/api/test" data-ajax--cache="true"&gt;&lt;/select&gt;
  42. </pre>
  43. <p>
  44. Which will be interpreted the same as initializing Select2 with...
  45. </p>
  46. <pre class="prettyprint linenums">
  47. $("select").select2({
  48. ajax: {
  49. url: "http://example.org/api/test",
  50. cache: "true"
  51. }
  52. });
  53. </pre>
  54. <p>
  55. The value of the option is subject to jQuery's
  56. <a href="https://api.jquery.com/data/#data-html5">parsing rules</a> for
  57. HTML5 data attributes.
  58. </p>
  59. </section>