data-attributes.html 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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" data-allow-clear="true"&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. allowClear: true
  28. });
  29. </pre>
  30. <h3>
  31. Are options with nested configurations supported?
  32. </h3>
  33. <p>
  34. You can also define nested configurations, which are typically needed for
  35. options such as AJAX. Each level of nesting should be separated by two
  36. dashes (<code>--</code>) instead of one. Due to
  37. <a href="https://github.com/jquery/jquery/issues/2070">a jQuery bug</a>,
  38. nested options using <code>data-*</code> attributes
  39. <a href="https://github.com/select2/select2/issues/2969">do not work in jQuery 1.x</a>.
  40. </p>
  41. <pre class="prettyprint">
  42. &lt;select data-ajax--url="http://example.org/api/test" data-ajax--cache="true"&gt;&lt;/select&gt;
  43. </pre>
  44. <p>
  45. Which will be interpreted the same as initializing Select2 with...
  46. </p>
  47. <pre class="prettyprint linenums">
  48. $("select").select2({
  49. ajax: {
  50. url: "http://example.org/api/test",
  51. cache: "true"
  52. }
  53. });
  54. </pre>
  55. <p>
  56. The value of the option is subject to jQuery's
  57. <a href="https://api.jquery.com/data/#data-html5">parsing rules</a> for
  58. HTML5 data attributes.
  59. </p>
  60. </section>