This documentation is set up in the form of a FAQ and covers the most common questions. If you do not find the answer to your question here, you may want to reach out to the community to see if someone else can answer it.
Core options
How should Select2 be initialized?
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.
1
$('select').select2();
You can optionally pass an object containing all of the options that you would like to initialize Select2 with.
1
2
3
$('select').select2({
placeholder: 'Select an option'
});
Can default options be set for all dropdowns?
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").
1
$.fn.select2.defaults.set("theme", "classic");
How can I set a default value for a nested option?
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.
1
$.fn.select2.defaults.set("ajax--cache", false);
How can I reset all of the global default options?
You can reset the default options to their initial values by calling
1
$.fn.select2.defaults.reset();
Can I declare my configuration within the HTML?
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.
How should 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...
1
<select data-tags="true" data-placeholder="Select an option" data-allow-clear="true"></select>
Will be interpreted the same as initializing Select2 as...
1
2
3
4
5
$("select").select2({
tags: "true",
placeholder: "Select an option",
allowClear: true
});
Are options with nested configurations supported?
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.
1
<select data-ajax--url="http://example.org/api/test" data-ajax--cache="true"></select>
Which will be interpreted the same as initializing Select2 with...
1
2
3
4
5
6
$("select").select2({
ajax: {
url: "http://example.org/api/test",
cache: true
}
});
The value of the option is subject to jQuery's parsing rules for HTML5 data attributes.
Can I use Select2 with my AMD or CommonJS loader?
Select2 should work with most AMD- or CommonJS-compliant module loaders, including RequireJS and almond. Select2 ships with a modified version of the UMD jQuery template that supports both CommonJS and AMD environments.
How do I tell Select2 where to look for modules?
For most AMD and CommonJS setups, the location of the data files used by Select2 will be automatically determined and handled without you needing to do anything.
If you are using Select2 in a build environment where preexisting module names are changed during a build step, Select2 may not be able to find optional dependencies or language files. You can manually set the prefixes to use for these files using the amdBase and amdLanugageBase options.
1
2
$.fn.select2.defaults.set('amdBase', 'select2/');
$.fn.select2.defaults.set('amdLanguageBase', 'select2/i18n/');
Select2 is being placed before jQuery in my JavaScript file
Due to a bug in older versions of the r.js build tool, Select2 was sometimes placed before jQuery in then compiled build file. Because of this, Select2 will trigger an error because it won't be able to find or load jQuery.
By upgrading to version 2.1.18 or higher of the r.js build tool, you will be able to fix the issue.
Should I point to the files in dist or src?
Select2 internally uses AMD and the r.js build tool to build the files located in the dist folder. These are built using the files in the src folder, so you can just point your modules to the Select2 source and load in jquery.select2 or select2/core when you want to use Select2. The files located in the dist folder are also AMD-compatible, so you can point to that file if you want to load in all of the default Select2 modules.
Data adapters
Can Select2 be used with a <select> tag?
Select2 was designed to be a replacement for the standard <select> boxes that are displayed by the browser, so by default it supports all options and operations that are available in a standard select box, but with added flexibility. There is no special configuration required to make Select2 work with a <select> tag.
Does Select2 support nesting options?
A standard <select> box can display nested options by wrapping them with in an <optgroup> tag.
1
2
3
4
5
<select>
<optgroup label="Group Name">
<option>Nested option</option>
</optgroup>
</select>
How many levels of nesting can there be?
Only a single level of nesting is allowed per the HTML specification. If you nest an <optgroup> within another <optgroup>, Select2 will not be able to detect the extra level of nesting and errors may be triggered as a result.
Can <optgroup> tags be made selectable?
No. This is a limitation of the HTML specification and is not a limitation that Select2 can overcome. You can emulate grouping by using an <option> instead of an <optgroup> and changing the style by using CSS, but this is not recommended as it is not fully accessible.
How are <option> and <optgroup> tags serialized into data objects?
Select2 will convert the <option> tag into a data object based on the following rules.
1
2
3
4
5
{
"id": "value attribute" || "option text",
"text": "label attribute" || "option text",
"element": HTMLOptionElement
}
And <optgroup> tags will be converted into data objects using the following rules
1
2
3
4
5
{
"text": "label attribute",
"children": [ option data object, ... ],
"elment": HTMLOptGroupElement
}
Can I load data into Select2 using an array?
While Select2 is designed to be used with a <select> tag
the data that is used to search through and display the results can be
loaded from a JavaScript array using the data option. This
option should be passed in during the initialization of Select2.
1
2
3
4
5
6
7
8
9
$('select').select2({
data: [
{
id: 'value',
text: 'Text to display'
},
// ... more data objects ...
]
});
What properties are required on the objects passed in to the array?
The id and text properties are required on each
object, and these are the properties that Select2 uses for the internal
data objects. Any additional paramters passed in with data objects will be
included on the data objects that Select2 exposes.
Do the id properties have to be strings?
Because the value attributes on a >select<
tag must be strings, the id property on the data objects must
also be strings. Select2 will attempt to convert anything that is not a
string to a string, which will work for most situations, but it is
recommended to force all of your ids to strings ahead of time.
I can't select results with blank ids or an id of 0!
See Do the id properties have to be strings?.
How should nested results be formatted?
Nested results should be specified using the children property
on the data objects that are passed in. This children property
should be an array of data objects that are grouped under this option, and
the label for the group should be specified as the text
property on the root data object.
1
2
3
4
5
6
7
8
9
10
{
text: 'Group label',
children: [
{
id: 'nested-1',
text: 'First nested option'
},
// ... more data objects ...
]
}
How many levels of nesting are allowed?
Because Select2 falls back to an <optgroup> when
creating nested options, only
a single level of nesting
is supported. Any additional levels of nesting is not guarenteed to be
displayed properly across all browsers and devices.
Why are <option> tags being created?
The data option is a shortcut that Select2 provides which
allows you to load options into your select from a data array.
My objects don't use id for their unique identifiers,
what can I do?
Select2 requires that the id property is used to uniquely
identify the options that are displayed in the results list. If you use a
property other than id (like pk) to uniquely
identify an option, you need to map your old property to id
before passing it to Select2.
If you cannot do this on your server or you are in a situation where the identifier cannot be changed, you can do this in JavaScript before passing it to Select2.
1
2
3
4
5
var data = $.map(yourArrayData, function (obj) {
obj.id = obj.id || obj.pk; // replace pk with your identifier
return obj;
});
My objects use a property other than text for the text that
needs to be displayed
Just like with the id property, Select2 requires that the text
that should be displayed for an option is stored in the text
property. You can map this property from any existing property using the
following JavaScript.
1
2
3
4
5
var data = $.map(yourArrayData, function (obj) {
obj.text = obj.text || obj.name; // replace name with the property used for the text
return obj;
});
Can Select2 be connected to a remote data source?
Select2 supports connecting to a remote data source using the ajax option.
How can I set the initially selected options when using AJAX?
You can refer to the following Stack Overflow answer if you want to set the initial value for AJAX requests: Select2 4.0.0 initial value with AJAX
What should the results returned to Select2 look like?
Is there a way to modify the response before passing it back to Select2?
You can use the ajax.processResults option to modify the data returned from the server before passing it to Select2.
1
2
3
4
5
6
7
8
9
10
$('select').select2({
ajax: {
url: '/example/api',
processResults: function (data) {
return {
results: data.items
};
}
}
});
A request is being triggered on every key stroke, can I delay this?
By default, Select2 will trigger a new AJAX request whenever the user changes their search term. You can set a time limit for debouncing requests using the ajax.delay option.
1
2
3
4
5
6
$('select').select2({
ajax: {
url: '/example/api',
delay: 250
}
});
This will tell Select2 to wait 250 milliseconds before sending the request out to your API.
How do I tell Select2 which URL to get the results from?
When connecting Select2 to a remote data source, you have the option of using either a single endpoint (a single page which handles all requests) or a dynamic endpoint (one of many pages). You can point Select2 to a single endpoint during initialization by specifying a string for the ajax.url option.
1
2
3
4
5
$('select').select2({
ajax: {
url: '/path/to/search/endpoint'
}
});
If there isn't a single url for your search results, or you need to call a function to determine the url to use, you can specify a function for the ajax.url option, and this will be used instead. The query parameters will be passed in through the params option.
1
2
3
4
5
6
7
$('select').select2({
ajax: {
url: function (params) {
return '/some/url/' + params.term;
}
}
});
I want to add more query parameters to the request, where can this be done?
By default, Select2 will send the query term as well as the pagination data as query parameters in requests. You can override the data that is sent to your API, or change any of the query paramters, by overriding the ajax.data option.
1
2
3
4
5
6
7
8
9
10
11
12
13
$('select').select2({
ajax: {
data: function (params) {
var query = {
search: params.term,
page: params.page
}
// Query paramters will be ?search=[term]&page=[page]
return query;
}
}
});
The results that I am seeing never change
Select2 expects that the results that are returned from the remote endpoint are already filtered ahead of time based on the search term. If your remote endpoint just returns the list of all possible options, you may be interested in using Select2's support for data arrays.
Can an AJAX plugin other than jQuery.ajax be used?
Select2 uses the transport method defined in ajax.transport to send requests to your API. By default, this transport method is jQuery.ajax but this can be changed.
1
2
3
4
5
6
7
8
9
$('select').select2({
ajax: {
transport: function (params, success, failure) {
var request = new AjaxRequest(params.url, params);
request.on('success', success);
request.on('failure', failure);
}
}
});
Displaying selections
Can I allow users to make multiple selections?
Yes, Select2 supports making multiple selections through the use of the multiple option that can be passed in when initializing Select2.
Can the multiple attribute be used on my <select> element?
Yes, Select2 will automatically map the value of the multiple attribute to the multiple option during initialization.
How can I have Select2 display a placeholder?
Select2 supports displaying a placeholder by default using the placeholder option. This can be either a data object matching the placeholder option, or a string to display as the placeholder if you are using a blank placeholder option.
1
2
3
$('select').select2({
placeholder: 'Select an option'
});
My first option is being displayed instead of my placeholder
This usually means that you do not have a blank <option></option> as the first option in your <select>.
Note that this does not apply to multiple selects, as the browser does not select the first option by default when multiple selections can be made.
I am using AJAX, can I still show a placeholder?
Yes, Select2 supports placeholders for all configurations. You will still need to add in the placeholder option if you are using a single select.
Can I use an option without a blank value as my placeholder?
The placeholder option allows you to pass in a data object instead of just a string if you need more flexibility. The id of the data object should match the value of the placeholder option.
1
2
3
4
5
6
$('select').select2({
placeholder: {
id: '-1', // the value of the option
text: 'Select an option'
}
});
Can I change how the placeholder looks?
When using Select2 when only a single selection can be made, the placeholder option will be passed through the standard templating methods, including the templateSelection option, so you are able to change how it is displayed.
1
2
3
4
5
6
7
8
9
$('select').select2({
templateResult: function (data) {
if (data.id === '') { // adjust for custom placeholder values
return 'Custom styled placeholder text';
}
return data.text;
}
});
When multiple selections are allowed, the placeholder will be displayed using the placeholder attribute on the search box. You can cusotmize the display of this placholder using CSS, as explained in the following Stack Overflow answer: Change an input's HTML5 placeholder color with CSS
My placeholders aren't being displayed in Internet Explorer
Select2 uses the native placeholder attribute on input boxes for the multiple select, and that attribute is not supported in older versions of Internet Explorer. You need to include Placeholders.js on your page, or use the full build, in order to add placeholder attribute support to input boxes.
Can I allow users to clear their selections?
You can allow people to clear their current selections with the allowClear option when initializing Select2. Setting this option to true will enable an "x" icon that will reset the selection to the placeholder.
1
2
3
4
$('select').select2({
placeholder: 'This is my placeholder',
allowClear: true
});
Why is a placeholder required?
The "x" icon is not clearing the selection
Can users remove all of their selections in a multiple select at once?
How can I customize the way selections are displayed?
When a selection is made by the user Select2 will display the text of the option by default, just like how it is displayed in a standard select box. You can override the display of the selection by setting the templateSelection option to a JavaScript function.
1
2
3
4
5
6
7
function template(data, container) {
return data.text;
}
$('select').select2({
templateSelection: template
});
Nothing is being displayed when I select an option
I am using HTML in my selection template but it isn't displaying it
How can I access the container where the selection is displayed?
Displaying results
Can I change when search results are loaded?
Can Select2 wait until the user has typed a search term before triggering the request?
1
2
3
4
5
$('select').select2({
ajax: {
delay: 250 // wait 250 milliseconds before triggering the request
}
});
Select2 is allowing long search terms, can this be prevented?
1
2
3
$('select').select2({
maximumInputLength: 20 // only allow terms up to 20 characters long
});
I only want the search box if there are enough results
1
2
3
$('select').select2({
minimumResultsForSearch: 20 // at least 20 results must be displayed
});
How can I permanently hide the search box?
1
2
3
$('select').select2({
minimumResultsForSearch: Infinity
});
Can I change how selecting results works?
Can I select the highlighted result when the dropdown is closed?
1
2
3
$('select').select2({
selectOnClose: true
});
Can I prevent the dropdown from closing when a result is selected?
1
2
3
$('select').select2({
closeOnSelect: false
});
Can options be created based on the search term?
How do I enable tagging?
1
2
3
$('select').select2({
tags: true
});
Does tagging work with a single select?
Yes.
How do I add extra properties to the tag?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$('select').select2({
createTag: function (params) {
var term = $.trim(params.term);
if (term === '') {
return null;
}
return {
id: term,
text: term,
newTag: true // add additional parameters
}
}
});
Can I control when tags are created?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
$('select').select2({
createTag: function (params) {
// Don't offset to create a tag if there is no @ symbol
if (params.term.indexOf('@') === -1) {
// Return null to disable tag creation
return null;
}
return {
id: params.term,
text: params.term
}
}
});
How do I control the placement of the option?
1
2
3
4
5
6
$('select').select2({
insertTag: function (data, tag) {
// Insert the tag at the end of the results
data.push(tag);
}
});
Can I change how the dropdown is placed?
Can the dropdown be placed directly after the selection container?
Can I pick an element for the dropdown to be appended to?
1
2
3
$('select').select2({
dropdownParent: $('#my_amazing_modal')
});
I'm using a Bootstrap modal and I can't use the search box
Use the dropdownParent option, setting it to the modal.
I'm using jQuery UI and I can't use the search box
Events
Public jQuery events
What events will Select2 trigger?
Select2 will trigger a few different events when different actions are taken using the component, allowing you to add custom hooks and perform actions.
- change
- Triggered whenever an option is selected or removed.
- select2:close
- Triggered whenever the dropdown is closed.
- select2:closing
- Triggered before the dropdown is closed. This event can be prevented.
- select2:open
- Triggered whenever the dropdown is opened.
- select2:opening
- Triggered before the dropdown is opened. This event can be prevented.
- select2:select
- Triggered whenever a result is selected.
- select2:selecting
- Triggered before a result is selected. This event can be prevented.
- select2:unselect
- Triggered whenever a selection is removed.
- select2:unselecting
- Triggered before a selection is removed. This event can be prevented.
Does Select2 include extra information in these events?
How can I attach listeners for these events?
1
2
3
$('select').on('select2:select', function (evt) {
// Do something
});
What events does Select2 listen for?
Select2 will listen for the change event on the
<select> that it is attached to. If you make any
external changes that need to be reflected in Select2 (such as changing the
value), you should trigger this event.
1
2
$('select').val('US'); // Select the option with a value of 'US'
$('select').trigger('change'); // Notify any JS components that the value changed
Can I trigger an event other than change to notify Select2 of changes?
It's common for other components to be listening to the change
event, or for custom event handlers to be attached that may have side
effects. Select2 does not have a custom event (like
select2:update) that can be triggered other than
change. You can rely on jQuery's event namespacing to limit
the scope to Select2 though by triggering the change.select2
event.
1
2
$('select').val('US'); // Change the value or make some change to the internal state
$('select').trigger('change.select2'); // Notify only Select2 of changes
What events can be prevented? How can I prevent a selection from being made?
Internal Select2 events
Select2 has an internal event system that works independently of the DOM event system. This internal event system is only accesssible from plugins and adapters that are connected to Select2.
Backwards compatibility
Simplified function for matching data objects
Added in Select2 4.0.0. This method was added to make upgrading easier from earlier versions of Select2.
During the Select2 4.0.0 release, the
matcher function was changed to allow for more complex
matching of nested objects.
- Key
-
matcher - Value
-
A function taking a search
termand the data objecttext.
- Adapter
-
oldMatcher
The custom matcher example provides a
guide for how to use this in your own application. For those upgrading
from older versions of Select2, you just need to wrap your old
matcher with this function to maintain compatibility.
Old initial selections with initSelection
Deprecated in Select2 4.0. This has been replaced by another option and is only available in the full builds of Select2.
In the past, Select2 required an option called initSelection
that was defined whenever a custom data source was being used, allowing
for the initial selection for the component to be determined. This has
been replaced by the current method on the
data adapter.
- Key
-
initSelection - Value
-
A function taking a
callback
- Adapter
-
DataAdapter - Decorator
-
InitSelection
Querying old data with query
Deprecated in Select2 4.0. This has been replaced by another option and is only available in the full builds of Select2.
In the past, Select2 supported an option called query that
allowed for a custom data source to be used. This option has been replaced
by the query method on the
data adapter and takes a very similar set of
parameters.
- Key
-
query - Value
-
A function taking
params(including acallback)
- Adapter
-
DataAdapter - Decorator
-
Query
Compatibility with <input type="text" />
Deprecated in Select2 4.0.
It is now encouraged to use the <select> tag instead.
In past versions of Select2, a <select> element could
only be used with a limited subset of options. An
<input type="hidden" /> was required instead, which did
not allow for a graceful fallback for users who did not have JavaScript
enabled. Select2 now supports the <select> element for
all options, so it is no longer required to use <input />
elements with Select2.
- Adapter
-
DataAdapter - Decorator
-
InputData
Select2