Select2 will register itself as a jQuery function if you use any of the distribution builds, so you can call .select2()
on any jQuery element where you would like to initialize Select2.
You can optionally pass an object containing all of the options that you would like to initialize Select2 with.
{% highlight js linenos %} $('select').select2({ placeholder: 'Select an option' }); {% endhighlight %}
In some cases, you need to set the default options for all instances of
Select2 in your web application. This is especially useful when you are
migrating from past versions of Select2, or you are using non-standard
options like custom AMD builds. Select2 exposes the
default options through $.fn.select2.defaults
, which allows
you to set them globally.
When setting options globally, any past defaults that have been set will be overriden. Default options are only used when an option is requested that has not been set during initialization.
You can set default options by calling
$.fn.select2.defaults.set("key", "value")
.
The key that is
set should take the same format as keys set using
HTML data-*
attributes which
means that two dashes (--
) will be replaced by a level of
nesting, and a single dash (-
) will convert it to a camelCase
string.
You can reset the default options to their initial values by calling
{% highlight js linenos %} $.fn.select2.defaults.reset(); {% endhighlight %}