Programmatic Access
-Select2 supports methods that allow programmatic control of the component
+Select2 supports methods that allow programmatic control of the component:
@@ -678,8 +678,8 @@ function format(state) {
Events
change
event is triggered on the original element whenever its value is changed by
- the user
open
event is triggered on the original element whenever the dropdown needs to be opened
open
event is triggered on the original element whenever the dropdown needs to be opened:
Tagging Support
-Select2 can be used to quickly set up fields used for tagging
+Select2 can be used to quickly set up fields used for tagging.
Note that when tagging is enabled the user can select from pre-existing tags or create a new tag by @@ -750,10 +750,10 @@ function format(state) {
Select2 supports ability to add choices automatically as the user is typing into the search field. This is especially convenient in the tagging usecase where the user can quickly enter a number of tags - by separating them with a comma or a space. Try typing in the search field below and entering a space or a comma
+ by separating them with a comma or a space. Try typing in the search field below and entering a space or a comma: -Note that the separators are defined in the tokenSeparators option
+Note that the separators are defined in the tokenSeparators option.
Note that this example uses the built in tokenizer function, but a custom one can be provided in the options.
Custom Matcher
-Unlike other dropdowns on this page, this one matches options only if the term appears in the beginning of the string as opposed to anywhere
+Unlike other dropdowns on this page, this one matches options only if the term appears in the beginning of the string as opposed to anywhere:
The dropdown below matches on custom attributes of the option
tag. For example, the `blue` option can be matched by entering either `blue` or `cyan`.
The dropdown below matches on custom attributes of the option
tag. For example, the `blue` option can be matched by entering either `blue` or `cyan`:
Example Code
--+
+
- 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 +
- 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.
The minimum number of results that must be initially (after opening the dropdown for the first time) @@ -1076,7 +1076,7 @@ function format(state) { 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.
-The option can be set to a negative value
to permanently hide the search field
The option can be set to a negative value
to permanently hide the search field.
Only applies to single-value select boxes
Once the number of selected items reaches the maximum specified the contents of the dropdown will be populated
- by the formatSelectionTooBig
function
formatSelectionTooBig
function.
This option only works 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
.
id(object)
Parameter | Type | Description |
---|---|---|
object | object | A choice object |
<returns> | string | the id of the object |
object | object | A choice object. |
<returns> | string | the id of the object. |
id
property that is returned.
matcher(term, text, option)
Parameter | Type | Description |
---|---|---|
term | string | search term |
text | string | text of the option being matched |
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 |
<returns> | boolean | true if search term matches the text, or false otherwise. |
function(term, text) { return text.toUpperCase().indexOf(term.toUpperCase())>=0; }
@@ -1197,9 +1197,9 @@ function format(state) {
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 |
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. |
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 |
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. |
escapeMarkup | function | Function that can be used to escape html markup. This is the function defined in the escapeMarkup option, or the default. |
<returns> | string (optional) | Html string, a DOM element, or a jQuery object that renders the selection |
<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
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 - } -+
+format(item) { + var originalOption = item.element; + return item.text +} +
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 |
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 |
<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
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 - } -+
+format(item) { + var originalOption = item.element; + return item.text +} +
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 |
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
By default when attached to a select
css classes from option
s will be automatically copied.
formatNoMatches(term)
Parameter | Type | Description |
---|---|---|
term | string | Search string entered by user |
<returns> | string | Message html |
term | string | Search string entered by user. |
<returns> | string | Message html. |
formatSearching()
Parameter | Type | Description |
---|---|---|
<returns> | string | Message html or null /undefined to disable the message |
<returns> | string | Message html or null /undefined to disable the message. |
formatInputTooShort(term, minLength)
Parameter | Type | Description |
---|---|---|
term | string | Search string entered by user |
minLength | int | Minimum required term length |
<returns> | string | Message html |
term | string | Search string entered by user. |
minLength | int | Minimum required term length. |
<returns> | string | Message html. |
formatSelectionTooBig(maxSize)
Parameter | Type | Description |
---|---|---|
maxSize | string | The maximum specified size of the selection |
<returns> | string | Message html |
maxSize | string | The maximum specified size of the selection. |
<returns> | string | Message html. |
createSearchChoice(term)
Parameter | Type | Description |
---|---|---|
term | string | Search string entered by user |
term | string | Search string entered by user. |
<returns> | object (optional) | Object representing the new choice.
Must at least contain an id attribute. |
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
,
as it is used as a value separator.
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 |
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 @@ -1356,14 +1356,14 @@ $("#select").select2({ 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 only applies to multi-selects.
tokenizer(input, selection, selectCallback, opts)
Parameter | Type | Description | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
input | string | The text entered into the search field so far | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
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 | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
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 @@ -1379,7 +1379,7 @@ $("#select").select2({ | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
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 [',', ' ']
+ tokenizer is disabled. Usually it is sensible to set this option to a value similar to [',', ' '] .
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
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.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:
| ||||||||||||||||||||||||
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. xml , json , jsonp , other formats supported by jquery | ||||||||||||||||||||||||
quietMillis | int | Number of milliseconds to wait for the user to stop typing before issuing the ajax request | ||||||||||||||||||||||||
cache | boolean | If set to false , it will force requested pages not to be cached by the browser. Default is false | ||||||||||||||||||||||||
dataType | string | Data type for the request. xml , json , jsonp , other formats supported by jquery. | ||||||||||||||||||||||||
quietMillis | int | Number of milliseconds to wait for the user to stop typing before issuing the ajax request. | ||||||||||||||||||||||||
cache | boolean | If set to false , it will force requested pages not to be cached by the browser. Default is false . | ||||||||||||||||||||||||
jsonpCallback | string/function | The callback function name for a JSONP request. This value will be used instead of the random name automatically generated by jQuery. It is preferable to let jQuery generate a unique name as it'll make it easier to manage the requests and provide callbacks and error handling. You may want to specify the callback when you want to enable better browser caching of GET requests. | ||||||||||||||||||||||||
data | function |
Function to generate query parameters for the ajax request.
data(term, page)
| ||||||||||||||||||||||||
results | function |
@@ -1464,8 +1464,8 @@ $("#select").select2({
results(data, page)
|
In order for this function to work Select2 should be attached to a input type='hidden'
tag instead of a select
.
For documentation of the data format see the query function
+For documentation of the data format see the query function.
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
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.
true
attempts to automatically size the width of the dropdown based on content inside.
@@ -1508,8 +1508,8 @@ $("#select").select2({
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 |
clazz | string | Css class being copied. |
<returns> | string | Css class to be applied or null/undefined/'' to not apply it. |
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 |
clazz | string | Css class being copied. |
<returns> | string | Css class to be applied or null/undefined/'' to not apply it. |
null
thereby filtering out all classes.
@@ -1528,12 +1528,35 @@ $("#select").select2({
Function used to post-process markup returned from formatter functions. By default this function escapes html entities to prevent javascript injection.
Set to true
if you want Select2 to select the currently highlighted option when it is blurred
Set to true
if you want Select2 to select the currently highlighted option when it is blurred.
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.
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.
+Function used to determine what the next search term should be.
+Parameter | Type | Description |
---|---|---|
data | object | Retrieved data. |
this.search.val() | string | Search term that yielded the current result set. |
Here is an example implementation used to display the current search term when the dropdown is opened:
++function displayCurrentValue(selectedObject, currentSearchTerm) { + return currentSearchTerm; +} +$("#e1").select2({ + nextSearchTerm: displayCurrentValue +}); ++
Only applies when the dropdown is configured in single-select mode.
+select
value
attribute of the option
that should be selectedvalue
attribute of the option
that should be selected.value
attributes of the option
s that should be selected. null
for empty.change
event should be triggered. false
by default.val
method invoked on a single-select with an unset value will return ""
, while a val
method invoked on an empty multi-select will return []
val
method invoked on a single-select with an unset value will return ""
, while a val
method invoked on an empty multi-select will return []
.
alert("Selected value is: "+$("#e8").select2("val")); $("#e8").select2("val", "CA");
Notice that in order to use this method you must define the initSelection
function in the options so Select2 knows how to transform the id of the object you pass in val()
to the full object it needs to render selection. If you are attaching to a select
element this function is already provided for you.
alert("Selected value is: "+$("#e8").select2("data
Gets or sets the selection. Analogous to val
method, but works with objects instead of ids.
data
method invoked on a single-select with an unset value will return null
, while a data
method invoked on an empty multi-select will return []
data
method invoked on a single-select with an unset value will return null
, while a data
method invoked on an empty multi-select will return []
.
alert("Selected value is: "+$("#e8").select2("-open
Opens the dropdown
+Opens the dropdown.
-close
Closes the dropdown
+Closes the dropdown.
@@ -1627,9 +1650,9 @@ Example:enable(boolean)
alert("Selected value is: "+$("#e8").select2("Fired when selection is changed.
The event object contains the following custom properties:
-
-
- val
- the current selection (taking into account the result of the change) - id or array of ids -
- added
- the added element, if any - the full element object, not just the id -
- removed
- the removed element, if any - the full element object, not just the id +
- val
- The current selection (taking into account the result of the change) - id or array of ids. +
- added
- The added element, if any - the full element object, not just the id. +
- removed
- The removed element, if any - the full element object, not just the id.
alert("Selected value is: "+$("#e8").select2("The event object contains the following custom properties:
-
-
- val
- the id of the highlighted choice object -
- object
- the highlighted choice object +
- val
- The id of the highlighted choice object. +
- object
- The highlighted choice object.
alert("Selected value is: "+$("#e8").select2("The event object contains the following custom properties:
-
-
- val
- the id of the highlighted choice object -
- object
- the choice object about to be selected +
- val
- The id of the highlighted choice object. +
- object
- The choice object about to be selected.
alert("Selected value is: "+$("#e8").select2("@@ -1704,14 +1727,14 @@ Example:@@ -1696,7 +1719,7 @@ Example:select2-removed
-Fired when a choice is removed or cleared
+Fired when a choice is removed or cleared.
The event object contains the following custom properties:
-
- val
- the id of the highlighted choice object
-- object
- the highlighted choice object
+- val
- The id of the highlighted choice object.
+- object
- The highlighted choice object.
alert("Selected value is: "+$("#e8").select2("The event object contains the following custom properties:
-
- items
- data that was used to populate the results
+- items
- Data that was used to populate the results.
alert("Selected value is: "+$("#e8").select2("select2-focus
-Fired when the control is focussed +
Fired when the control is focussed.
@@ -1720,8 +1743,7 @@ Example:select2-blur
-Fired when the control is blurred +
Fired when the control is blurred.
alert("Selected value is: "+$("#e8").select2("diff --git a/select2-latest.html b/select2-latest.html index aec54773..261cbaa0 100644 --- a/select2-latest.html +++ b/select2-latest.html @@ -376,7 +376,7 @@ $("#e10_4").select2({Configuring Defaults
- Select2 exposes its default options via the$.fn.select2.defaults
object. Properties changed in this object (same properties configurable through the constructor) will take effect for every instance created after the change - + Select2 exposes its default options via the$.fn.select2.defaults
object. Properties changed in this object (same properties configurable through the constructor) will take effect for every instance created after the change.-
with support for quick option filtering via a search box
+with support for quick option filtering via a search box.
Example Code
@@ -436,7 +436,7 @@ $("#e2_2").select2({-
The placeholder can be declared via a
+data-placeholder
attribute attached to theselect
, or via theplaceholder
configuration element as seen in the example codeThe placeholder can be declared via a
data-placeholder
attribute attached to theselect
, or via theplaceholder
configuration element as seen in the example code.When placeholder is used for a non-multi-value select box, it requires that you include an empty
<option></option>
tag as your first option.Optionally, a clear button (visible once a selection is made) is available to reset the select box back to the placeholder value.
@@ -569,7 +569,7 @@ $("#e19").select2({ maximumSelectionSize: 3 });If this example does not work it is probably because the Rotten Tomatoes API key usage of 10000 requests per day has been exhausted. Please try again tomorrow.
Example Code
-Select2 uses jQuery's
+$.ajax
function to execute the remote call by default. An alternativetransport
function can be specified in the ajax settings, or an entirely custom implementation can be built by providing a customquery
function instead of using theajax
helperSelect2 uses jQuery's
$.ajax
function to execute the remote call by default. An alternativetransport
function can be specified in the ajax settings, or an entirely custom implementation can be built by providing a customquery
function instead of using theajax
helper.