It is recommended that you declare your configuration options for Select2
when initializing Select2. You can also define your configuration options
by using the HTML5 data-*
attributes, which will override
any options set when initializing Select2 and any defaults.
camelCase
options be written?
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 allowClear
should instead be defined as allow-clear
.
This means that if you declare your <select>
tag as...
Will be interpreted the same as initializing Select2 as...
{% highlight js linenos %} $("select").select2({ tags: "true", placeholder: "Select an option", allowClear: true }); {% endhighlight %}
You can also define nested configurations, which are typically needed for
options such as AJAX. Each level of nesting should be separated by two
dashes (--
) instead of one. Due to
a jQuery bug,
nested options using data-*
attributes
do not work in jQuery 1.x.
Which will be interpreted the same as initializing Select2 with...
{% highlight js linenos %} $("select").select2({ ajax: { url: "http://example.org/api/test", cache: true } }); {% endhighlight %}The value of the option is subject to jQuery's parsing rules for HTML5 data attributes.