Parameter | Type | Description |
width | string |
Controls the width style attribute of the Select2 container div. The following values are supported:
- off
- No width attribute will be set. Keep in mind that the container div copies classes from the source element so setting the width attribute may not always be necessary.
- element
- Uses javascript to calculate the width of the source element.
- copy
- Copies the value of the width style attribute set on the source element
- resolve
- First attempts to copy than falls back on element
- other values
- if the width attribute contains a function it will be avaluated, otherwise the value is used verbatim
|
minimumInputLength | int | Number of characters necessary to start a search |
maximumInputLength | int | Maximum number of characters that can be entered for an input |
minimumResultsForSearch | int |
The minimum number of results that must be initially (after opening the dropdown for the first time)
populated in order to keep the search field. This
is useful for cases where local data is used with just a few results, in which case the search box
is not very useful and wastes screen space.
Only applies to single-value select boxes
|
maximumSelectionSize | int/function |
The maximum number of items that can be selected in a multi-select control. If this number is less than 1 selection is not limited.
Once the number of selected items reaches the maximum specified the contents of the dropdown will be populated
by the formatSelectionTooBig function
|
placeholder | string |
Initial value that is selected if no other selection is made.
The placeholder can also be specified as a data-placeholder attribute on the select
or input element that Select2 is attached to.
Note that because browsers assume the first option element
is selected in non-multi-value select boxes an empty first option element must be provided (<option></option> )
for the placeholder to work.
|
separator | string |
Separator character or string used to delimit ids in value attribute of the multi-valued selects.
The default delimiter is the , character.
|
allowClear |
boolean |
Whether or not a clear button is displayed when the select box has a selection. The
button,
when clicked, resets the value of the select box back to the placeholder, thus this option is
only
available when the placeholder is specified.
This option only works when the placeholder is specified
When attached to a select an option with an empty value must be provided.
This is the option that will be selected when the button is pressed since a select box requires
at least one selection option .
Also, note that this option only works with
non-multi-value based selects because multi-value selects always provide such a button for every
selected option.
|
multiple |
boolean |
Whether or not Select2 allows selection of multiple values.
When Select2 is attached to a select element this value will be ignored and select 's
multiple attribute will be used instead.
|
closeOnSelect |
boolean |
If set to true the dropdown is not closed after a selection is made, allowing for rapid selection of multiple items. By default this option is disabled.
Only applies when configured in multi-select mode.
|
openOnEnter |
boolean |
If set to true the dropdown is opened when the user presses the enter key and Select2 is closed. By default this option is enabled.
|
id | function |
Function used to get the id from the choice object or a string representing the key under which the id is stored.
id(object)
Parameter | Type | Description |
object | object | A choice object |
<returns> | string | the id of the object |
The default implementation expects the object to have a id property that is returned.
|
matcher | function |
Used to determine whether or not the search term matches an option when a built-in query function is used.
The built in query function is used when Select2 is attached to a select , or the local or tags helpers are used.
matcher(term, text, option)
Parameter | Type | Description |
term | string | search term |
text | string | text of the option being matched |
option | jquery object |
the option element we are trying to match. Only given when attached to select .
Can be used to match against custom attributes on the option tag in addition to matching on the option 's text. |
<returns> | boolean | true if search term matches the text, or false otherwise |
The default implementation is case insensitive and matches anywhere in the term:
function(term, text) { return text.toUpperCase().indexOf(term.toUpperCase())>=0; }
|
sortResults | function |
Used to sort the results list for searching right before display. Useful for sorting matches by relevance to the user's search term.
sortResults(results, container, query)
object | object | One of the result objects returned from the query function |
container | jQuery object | jQuery wrapper of the node that should contain the representation of the result |
query | object | The query object used to request this set of results |
<returns> | object | A results object. |
Defaults to no sorting:
function(results, container, query) { return results; }
|
formatSelection | function |
Function used to render the current selection.
formatSelection(object, container)
Parameter | Type | Description |
object | object | The selected result object returned from the query function |
container | jQuery object | jQuery wrapper of the node to which the selection should be appended |
<returns> | string (optional) | Html string, a DOM element, or a jQuery object that renders the selection |
The default implementation expects the object to have a text property that is returned.
The implementation may choose to append elements directly to the provided container object, or return a single value and have it automatically appended
When attached to a select the original <option> (or <optgroup>) element is accessible inside the specified function through the property item.element :
format(item) {
var originalOption = item.element;
return item.text
}
|
formatResult | function |
Function used to render a result that the user can select.
formatResult(object, container, query)
Parameter | Type | Description |
object | object | One of the result objects returned from the query function |
container | jQuery object | jQuery wrapper of the node that should contain the representation of the result |
query | object | The query object used to request this set of results |
escapeMarkup | function | Function used to escape markup in results. If you do not expect to render custom markup you should pass your text through this function to escape any markup that may have been accidentally returned. This function is configurable in options of select2. |
<returns> | string (optional) | Html string, a DOM element, or a jQuery object that represents the result |
The default implementation expects the object to have a text property that is returned.
The implementation may choose to append elements directly to the provided container object, or return a single value and have it automatically appended
When attached to a select the original <option> (or <optgroup>) element is accessible inside the specified function through the property item.element :
format(item) {
var originalOption = item.element;
return item.text
}
|
formatResultCssClass | function |
Function used to add css classes to result elements
formatResultCssClass(object)
Parameter | Type | Description |
object | object | One of the result objects returned from the query function |
<returns> | string (optional) | String containing css class names separated by a space |
By default when attached to a select css classes from option s will be automatically copied
|
formatNoMatches | function |
Function used to render the "No matches" message
formatNoMatches(term)
Parameter | Type | Description |
term | string | Search string entered by user |
<returns> | string | Message html |
|
formatSearching | function |
Function used to render the "Searching..." message that is displayed while
search is in progress
formatSearching()
Parameter | Type | Description |
<returns> | string | Message html or null /undefined to disable the message |
|
formatInputTooShort | function |
Function used to render the "Search input too short" message
formatInputTooShort(term, minLength)
Parameter | Type | Description |
term | string | Search string entered by user |
minLength | int | Minimum required term length |
<returns> | string | Message html |
|
formatSelectionTooBig | function |
Function used to render the "You cannot select any more choices" message
formatSelectionTooBig(maxSize)
Parameter | Type | Description |
maxSize | string | The maximum specified size of the selection |
<returns> | string | Message html |
|
createSearchChoice | function |
Creates a new selectable choice from user's search term. Allows creation of choices not available via the query
function. Useful when the user can create choices on the fly, eg for the 'tagging' usecase.
createSearchChoice(term)
Parameter | Type | Description |
term | string | Search string entered by user |
<returns> | object (optional) | Object representing the new choice.
Must at least contain an id attribute. |
If the function returns undefined or null no choice will be created. If a new
choice is created it is displayed first in the selection list so that user may select it by simply pressing
enter .
When used in combination with input[type=hidden] tag care
must be taken to sanitize the id attribute of the choice object, especially stripping
, as it is used as a value separator
|
initSelection | function |
Called when Select2 is created to allow the user to initialize the selection based on the value of the
element select2 is attached to.
Essentially this is an id->object mapping function.
initSelection(element, callback)
Parameter | Type | Description |
element | jQuery array | element Select2 is attached to |
callback | function | callback function that should be called with the data which is either an object in case of a single select or an array of objects in case of multi-select |
This function will only be called when there is initial input to be processed.
Here is an example implementation used for tags. Tags are the simplest form of data where the id is also
the text:
$("#tags").select2({
initSelection : function (element, callback) {
var data = [];
$(element.val().split(",")).each(function () {
data.push({id: this, text: this});
});
callback(data);
}
});
|
tokenizer | function |
A tokenizer function can process the input typed into the search field after every keystroke and extract
and select choices. This is useful, for example, in tagging scenarios where the user can create tags quickly
by separating them with a comma or a space instead of pressing enter.
Tokenizer only applies to multi-selects
tokenizer(input, selection, selectCallback, opts)
Parameter | Type | Description |
input | string | The text entered into the search field so far |
selection | array | Array of objects representing the current selection.
Useful if tokenizer needs to filter out duplicates. |
selectCallback | function | Callback that can be used to add objects to the selection |
opts | object | Options with which Select2 was initialized. Useful if tokenizer needs to access some properties in the options. |
<returns> | string (optional) | Returns the string to which the input of
the search field should be set to. Usually this is the remainder, of any, of the string after
the tokens have been stripped. If undefined or null is returned the
input of the search field is unchanged. |
The default tokenizer will only be used if the tokenSeparators and createSearchChoice
options are specified. The default tokenizer will split the string using any separator in tokenSeparators
and will create and select choice objects using createSearhChoice option. It will also
ignore duplicates, silently swallowing those tokens.
|
tokenSeparators | array |
An array of strings that define token separators for the default tokenizer
function. By default, this option is set to an empty array which means tokenization using the default
tokenizer is disabled. Usually it is sensible to set this option to a value similar to [',', ' ']
|
query |
function |
Function used to query results for the search term.
query(options)
Parameter | Type | Description |
options.element | jquery object | The element Select2 is attached to |
options.term | string | Search string entered by user |
options.page | int | 1-based page number tracked by Select2 for use with infinite scrolling of results |
options.context | object | An object that persists across the lifecycle of queries for the same search term (the query to retrieve the initial results, and subsequent queries to retrieve more result pages for the same search term). When this function is first called for a new search term this object will be null. The user may choose to set any object in the results.context field - this object will then be used as the context parameter for all calls to the query method that will load more search results for the initial search term. The object will be reset back to null when a new search term is queried. This feature is useful when a page number is not easily mapped against the server side paging mechanism. For example, some server side paging mechanism may return a "continuation token" that needs to be passed back to them in order to retrieve the next page of search results. |
options.callback | function |
Callback function that should be called with the result object. The result object:
Parameter | Type | Description |
result.results | [object] | Array of result objects. The default renderers expect objects with id and text keys. The id attribute is required, even if custom renderers are used. The object may also contain a children key if hierarchical data is displayed. |
result.more | boolean | true if more results are available for the current search term |
results.context | object | A user-defined object that should be made available as the context parameter to the query function on subsequent queries to load more result pages for the same search term. See the description of options.context parameter. |
|
In order for this function to work Select2 should be attached to a input type='hidden' tag instead of a select .
Example Data
{
more: false,
results: [
{ id: "CA", text: "California" },
{ id: "AL", text: "Alabama" }
]
}
Example Hierarchical Data
{
more: false,
results: [
{ text: "Western", children: [
{ id: "CA", text: "California" },
{ id: "AZ", text: "Arizona" }
] },
{ text: "Eastern", children: [
{ id: "FL", text: "Florida" }
] }
]
}
|
ajax | object |
Options for the built in ajax query function. This object acts as a shortcut for having to manually write a function that performs ajax requests. The built-in function supports more advanced features such as throttling and dropping out-of-order responses.
Parameter | Type | Description |
transport | function | Function that will be used to perform the ajax request. Must be parameter-compatible with $.ajax . Defaults to $.ajax if not specified.
Allows the use of various ajax wrapper libraries such as: AjaxManager. |
url | string/function | String containing the ajax url or a function that returns such a string. |
dataType | string | Data type for the request. ajax , jsonp , other formats supported by jquery |
quietMillis | int | Number of milliseconds to wait for the user to stop typing before issuing the ajax request |
data | function |
Function to generate query parameters for the ajax request.
data(term, page)
Parameter | Type | Description |
term | string | Search term |
page | int | 1-based page number tracked by Select2 for use with infinite scrolling of results |
context | object | See options.context parameter to the query function above. |
<returns> | object | Object containing url paramters |
|
results | function |
Function used to build the query results object from the ajax response
results(data, page)
Parameter | Type | Description |
data | object | Retrieved data |
page | int | Page number that was passed into the data function above |
context | object | See options.context parameter to the query function above. |
<returns> | object | Results object. See "options.callback" in the "query" function for format. |
|
params | object/function | An object or a function that returns an object that contains extra parameters that will be passed to the transport. For example it can be used to set the content type: {contentType: "application/json;charset=utf-8"} |
In order for this function to work Select2 should be attached to a input type='hidden' tag instead of a select .
|
data | array/object |
Options for the built in query function that works with arrays.
If this element contains an array, each element in the array must contain id and text keys
Alternatively, this element can be specified as an object in which results key must contain the data as an array and a text key can either be the name of the key in data items that contains text or a function that retrieves the text given a data element from the array
|
tags | array/function |
Puts Select2 into 'tagging'mode where the user can add new choices and pre-existing tags are provided via
this options attribute which is either an array or a function that returns an
array of objects or strings . If strings are used instead of objects
they will be converted into an object that has an id and text attribute equal
to the value of the string .
|
containerCss | function/object |
Inline css that will be added to select2's container. Either an object containing css property/value key pairs or a function that returns such an object.
|
containerCssClass | function/string |
Css class that will be added to select2's container tag
|
dropdownCss | function/object |
Inline css that will be added to select2's dropdown container. Either an object containing css property/value key pairs or a function that returns such an object.
|
dropdownCssClass | function/string |
Css class that will be added to select2's dropdown container
|
adaptContainerCssClass | function |
Function that filters/renames css classes as they are copied from the source tag to the select2 container tag.
adaptContainerCssClass(clazz)
Parameter | Type | Description |
clazz | string | Css class being copied |
<returns> | string | Css class to be applied or null/undefined/'' to not apply it |
The default implementation applies all classes without modification.
|
adaptDropdownCssClass | function |
Function that filters/renames css classes as they are copied from the source tag to the select2 dropdown tag.
adaptDropdownCssClass(clazz)
Parameter | Type | Description |
clazz | string | Css class being copied |
<returns> | string | Css class to be applied or null/undefined/'' to not apply it |
The default implementation always returns null thereby filtering out all classes.
|
escapeMarkup | function |
String escapeMarkup(String markup)
Function used to post-process markup returned from formatter functions. By default this function escapes html entities to prevent javascript injection.
|
selectOnBlur | boolean |
Set to true if you want Select2 to select the currently highlighted option when it is blurred
|
loadMorePadding | integer |
Defines how many results need to be below the fold before the next page is loaded. The default value is 0 which means the result list needs to be scrolled all the way to the bottom for the next page of results to be loaded. This option can be used to trigger the load sooner, possibly resulting in a smoother user experience.
|
Gets or sets the selection. If the value
parameter is not specified, the id
attribute of the currently selected element is returned. If the value
parameter is specified it will become the current selection.
Gets or sets the selection. Analogous to val
method, but works with objects instead of ids.
Reverts changes to DOM done by Select2. Any selection done via Select2 will be preserved.
Disables Select2. During this mode the user is not allowed to manipulate the selection.
Enables Select2.
Retrieves the main container element that wraps all of DOM added by Select2
Example: console.log($("#tags").select2("container"));
Notifies Select2 that a drag and drop sorting operation has started. Select2 will hide all non-selection list items such as the search container, etc.
Example: $("#tags").select2("onSortStart");
Notifies Select2 that a drag and drop sorting operation has finished. Select2 will re-display any elements previously hidden and update the selection of the element it is attached to.
Example: $("#tags").select2("onSortEnd");