data-attributes.html 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. HTML data attributes are case-insensitive, so any options which contain capital letters will be parsed as if they were all lowercase. Because Select2 has many options which are camelCase, where words are separated by uppercase letters, you must write these options out with dashes instead. So an option that would normally be called <code>allowClear</code> should instead be defined as <code>allow-clear</code>.
  16. </p>
  17. <p>
  18. This means that if you declare your <code>&lt;select&gt;</code> tag as...
  19. </p>
  20. {% highlight html linenos %}
  21. <select data-tags="true" data-placeholder="Select an option" data-allow-clear="true"></select>
  22. {% endhighlight %}
  23. <p>
  24. Will be interpreted the same as initializing Select2 as...
  25. </p>
  26. {% highlight js linenos %}
  27. $("select").select2({
  28. tags: "true",
  29. placeholder: "Select an option",
  30. allowClear: true
  31. });
  32. {% endhighlight %}
  33. <h3>
  34. Are options with nested configurations supported?
  35. </h3>
  36. <p>
  37. You can also define nested configurations, which are typically needed for
  38. options such as AJAX. Each level of nesting should be separated by two
  39. dashes (<code>--</code>) instead of one. Due to
  40. <a href="https://github.com/jquery/jquery/issues/2070">a jQuery bug</a>,
  41. nested options using <code>data-*</code> attributes
  42. <a href="https://github.com/select2/select2/issues/2969">do not work in jQuery 1.x</a>.
  43. </p>
  44. {% highlight html linenos %}
  45. <select data-ajax--url="http://example.org/api/test" data-ajax--cache="true"></select>
  46. {% endhighlight %}
  47. <p>
  48. Which will be interpreted the same as initializing Select2 with...
  49. </p>
  50. {% highlight js linenos %}
  51. $("select").select2({
  52. ajax: {
  53. url: "http://example.org/api/test",
  54. cache: true
  55. }
  56. });
  57. {% endhighlight %}
  58. <p>
  59. The value of the option is subject to jQuery's
  60. <a href="https://api.jquery.com/data/#data-html5">parsing rules</a> for
  61. HTML5 data attributes.
  62. </p>
  63. </section>