From 6eeebc325b4b6ae892f6571aa32f0c18dcaf9cff Mon Sep 17 00:00:00 2001 From: jdecuyper Date: Thu, 29 Aug 2013 16:53:53 -0500 Subject: [PATCH] Add documentation for the nextSearchTerm function --- index.html | 252 ++++++++++++++++++++++++-------------------- select2-latest.html | 248 +++++++++++++++++++++++-------------------- 2 files changed, 271 insertions(+), 229 deletions(-) diff --git a/index.html b/index.html index f1984f74..4d748afd 100644 --- a/index.html +++ b/index.html @@ -364,7 +364,7 @@ milestone: 12

-

with support for quick option filtering via a search box

+

with support for quick option filtering via a search box.

Example Code

@@ -424,7 +424,7 @@ milestone: 12


-

The placeholder can be declared via a data-placeholder attribute attached to the select, or via the placeholder configuration element as seen in the example code

+

The placeholder can be declared via a data-placeholder attribute attached to the select, or via the placeholder 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.

@@ -557,7 +557,7 @@ function format(state) {

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 alternative transport function can be specified in the ajax settings, or an entirely custom implementation can be built by providing a custom query function instead of using the ajax helper

+

Select2 uses jQuery's $.ajax function to execute the remote call by default. An alternative transport function can be specified in the ajax settings, or an entirely custom implementation can be built by providing a custom query function instead of using the ajax helper.

@@ -600,7 +600,7 @@ function format(state) {

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

+ the user.

+

open event is triggered on the original element whenever the dropdown needs to be opened:

@@ -702,7 +702,7 @@ function format(state) {

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.

@@ -890,9 +890,9 @@ function format(state) {

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`:

@@ -957,8 +957,8 @@ function format(state) {

Example Code

-
-           
+
+   
@@ -1062,13 +1062,13 @@ function format(state) {
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.
-minimumInputLengthintNumber of characters necessary to start a search -maximumInputLengthintMaximum number of characters that can be entered for an input +minimumInputLengthintNumber of characters necessary to start a search. +maximumInputLengthintMaximum number of characters that can be entered for an input. minimumResultsForSearchint

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

@@ -1085,7 +1085,7 @@ function format(state) { 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

+ by the formatSelectionTooBig function.

placeholderstring @@ -1122,7 +1122,7 @@ function format(state) { only available when the placeholder is specified.

-

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.

@@ -1172,8 +1172,8 @@ function format(state) {
id(object)
- - + +
ParameterTypeDescription
objectobjectA choice object
<returns>stringthe id of the object
objectobjectA choice object.
<returns>stringthe id of the object.
The default implementation expects the object to have a id property that is returned. @@ -1183,12 +1183,12 @@ function format(state) {
matcher(term, text, option)
- - + + - +
ParameterTypeDescription
termstringsearch term
textstringtext of the option being matched
termstringsearch term.
textstringtext of the option being matched.
optionjquery 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>booleantrue if search term matches the text, or false otherwise
<returns>booleantrue 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; } @@ -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)
- - - + + +
objectobjectOne of the result objects returned from the query function
containerjQuery objectjQuery wrapper of the node that should contain the representation of the result
queryobjectThe query object used to request this set of results
objectobjectOne of the result objects returned from the query function.
containerjQuery objectjQuery wrapper of the node that should contain the representation of the result.
queryobjectThe query object used to request this set of results.
<returns>objectA results object.
Defaults to no sorting: @@ -1210,22 +1210,22 @@ function format(state) {
formatSelection(object, container)
- - + + - +
ParameterTypeDescription
objectobjectThe selected result object returned from the query function
containerjQuery objectjQuery wrapper of the node to which the selection should be appended
objectobjectThe selected result object returned from the query function.
containerjQuery objectjQuery wrapper of the node to which the selection should be appended.
escapeMarkupfunctionFunction that can be used to escape html markup. This is the function defined in the escapeMarkupoption, 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
+}
+

formatResultfunction @@ -1233,70 +1233,70 @@ function format(state) {
formatResult(object, container, query)
- - - + + + - +
ParameterTypeDescription
objectobjectOne of the result objects returned from the query function
containerjQuery objectjQuery wrapper of the node that should contain the representation of the result
queryobjectThe query object used to request this set of results
objectobjectOne of the result objects returned from the query function.
containerjQuery objectjQuery wrapper of the node that should contain the representation of the result.
queryobjectThe query object used to request this set of results.
escapeMarkupfunctionFunction 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
+}
+

formatResultCssClassfunction - Function used to add css classes to result elements + Function used to add css classes to result elements.
formatResultCssClass(object)
- - + +
ParameterTypeDescription
objectobjectOne of the result objects returned from the query function
<returns>string (optional)String containing css class names separated by a space
objectobjectOne 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 options will be automatically copied

+

By default when attached to a select css classes from options will be automatically copied.

formatNoMatchesfunction Function used to render the "No matches" message
formatNoMatches(term)
- - + +
ParameterTypeDescription
termstringSearch string entered by user
<returns>stringMessage html
termstringSearch string entered by user.
<returns>stringMessage html.
formatSearchingfunction Function used to render the "Searching..." message that is displayed while - search is in progress + search is in progress.
formatSearching()
- +
ParameterTypeDescription
<returns>stringMessage html or null/undefined to disable the message
<returns>stringMessage html or null/undefined to disable the message.
formatInputTooShortfunction - Function used to render the "Search input too short" message + Function used to render the "Search input too short" message.
formatInputTooShort(term, minLength)
- - - + + +
ParameterTypeDescription
termstringSearch string entered by user
minLengthintMinimum required term length
<returns>stringMessage html
termstringSearch string entered by user.
minLengthintMinimum required term length.
<returns>stringMessage html.
formatSelectionTooBigfunction - Function used to render the "You cannot select any more choices" message + Function used to render the "You cannot select any more choices" message.
formatSelectionTooBig(maxSize)
- - + +
ParameterTypeDescription
maxSizestringThe maximum specified size of the selection
<returns>stringMessage html
maxSizestringThe maximum specified size of the selection.
<returns>stringMessage html.
createSearchChoicefunction @@ -1305,7 +1305,7 @@ function format(state) {
createSearchChoice(term)
- +
ParameterTypeDescription
termstringSearch string entered by user
termstringSearch string entered by user.
<returns>object (optional)Object representing the new choice. Must at least contain an id attribute.
@@ -1315,7 +1315,7 @@ function format(state) {

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.

initSelectionfunction Called when Select2 is created to allow the user to initialize the selection based on the value of the @@ -1326,8 +1326,8 @@ function format(state) {
initSelection(element, callback)
- - + +
ParameterTypeDescription
elementjQuery arrayelement Select2 is attached to
callbackfunctioncallback 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
elementjQuery arrayelement Select2 is attached to.
callbackfunctioncallback 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)
- + - + @@ -1390,16 +1390,16 @@ $("#select").select2({
query(options)
ParameterTypeDescription
inputstringThe text entered into the search field so far
inputstringThe text entered into the search field so far.
selectionarrayArray of objects representing the current selection. Useful if tokenizer needs to filter out duplicates.
selectCallbackfunctionCallback that can be used to add objects to the selection
selectCallbackfunctionCallback that can be used to add objects to the selection.
optsobjectOptions 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({
tokenSeparatorsarray 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 [',', ' '].
- - - + + + @@ -1444,19 +1444,19 @@ $("#select").select2({ - - - + + +
ParameterTypeDescription
options.elementjquery objectThe element Select2 is attached to
options.termstringSearch string entered by user
options.pageint1-based page number tracked by Select2 for use with infinite scrolling of results
options.elementjquery objectThe element Select2 is attached to.
options.termstringSearch string entered by user.
options.pageint1-based page number tracked by Select2 for use with infinite scrolling of results.
options.contextobjectAn 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.callbackfunction Callback function that should be called with the result object. The result object: - +
ParameterTypeDescription
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 childrenkey if hierarchical data is displayed.
result.morebooleantrueif more results are available for the current search term
result.morebooleantrueif more results are available for the current search term.
results.contextobjectA 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.
transportfunctionFunction 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.
urlstring/functionString containing the ajax url or a function that returns such a string.
dataTypestringData type for the request. xml, json, jsonp, other formats supported by jquery
quietMillisintNumber of milliseconds to wait for the user to stop typing before issuing the ajax request
cachebooleanIf set to false, it will force requested pages not to be cached by the browser. Default is false
dataTypestringData type for the request. xml, json, jsonp, other formats supported by jquery.
quietMillisintNumber of milliseconds to wait for the user to stop typing before issuing the ajax request.
cachebooleanIf set to false, it will force requested pages not to be cached by the browser. Default is false.
jsonpCallbackstring/functionThe 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.
datafunction Function to generate query parameters for the ajax request.
data(term, page)
- - + + - +
ParameterTypeDescription
termstringSearch term
pageint1-based page number tracked by Select2 for use with infinite scrolling of results
termstringSearch term.
pageint1-based page number tracked by Select2 for use with infinite scrolling of results.
contextobjectSee options.context parameter to the query function above.
<returns>objectObject containing url paramters
<returns>objectObject containing url parameters.
resultsfunction @@ -1464,8 +1464,8 @@ $("#select").select2({
results(data, page)
- - + +
ParameterTypeDescription
dataobjectRetrieved data
pageintPage number that was passed into the data function above
dataobjectRetrieved data.
pageintPage number that was passed into the data function above.
contextobjectSee options.context parameter to the query function above.
<returns>objectResults object. See "options.callback" in the "query" function for format.
@@ -1474,12 +1474,12 @@ $("#select").select2({

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.

dataarray/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

+

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.

tagsarray/function Puts Select2 into 'tagging'mode where the user can add new choices and pre-existing tags are provided via @@ -1492,13 +1492,13 @@ $("#select").select2({ 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. containerCssClassfunction/string - Css class that will be added to select2's container tag + Css class that will be added to select2's container tag. dropdownCssfunction/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. dropdownCssClassfunction/string - Css class that will be added to select2's dropdown container + Css class that will be added to select2's dropdown container. dropdownAutoWidthboolean When set to true attempts to automatically size the width of the dropdown based on content inside. @@ -1508,8 +1508,8 @@ $("#select").select2({
adaptContainerCssClass(clazz)
- - + +
ParameterTypeDescription
clazzstringCss class being copied
<returns>stringCss class to be applied or null/undefined/'' to not apply it
clazzstringCss class being copied.
<returns>stringCss class to be applied or null/undefined/'' to not apply it.
The default implementation applies all classes without modification. @@ -1518,8 +1518,8 @@ $("#select").select2({
adaptDropdownCssClass(clazz)
- - + +
ParameterTypeDescription
clazzstringCss class being copied
<returns>stringCss class to be applied or null/undefined/'' to not apply it
clazzstringCss class being copied.
<returns>stringCss class to be applied or null/undefined/'' to not apply it.
The default implementation always returns 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.

selectOnBlurboolean -

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.

loadMorePaddinginteger Defines how many pixels 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. +loadMorePaddinginteger + Defines how many pixels 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. + +nextSearchTermfunction +

Function used to determine what the next search term should be.

+ + + + + + +
ParameterTypeDescription
dataobjectRetrieved data.
this.search.val()stringSearch 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.

+
@@ -1552,7 +1575,7 @@ $("#select").select2({ Attached to select - Value of the value attribute of the option that should be selected + Value of the value attribute of the option that should be selected. Array of the value attributes of the options that should be selected. null for empty. @@ -1565,7 +1588,7 @@ $("#select").select2({ triggerChange (optional)booleanWhether or not a 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 [].

Example:
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.

@@ -1574,7 +1597,7 @@ Example:
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 [].

@@ -1585,11 +1608,11 @@ Example:
alert("Selected value is: "+$("#e8").select2("
 

open

-

Opens the dropdown

+

Opens the dropdown.

close

-

Closes the dropdown

+

Closes the dropdown.

enable(boolean)

@@ -1627,9 +1650,9 @@ Example:
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.

@@ -1656,8 +1679,8 @@ Example:
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.

@@ -1670,8 +1693,8 @@ Example:
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.

@@ -1679,12 +1702,12 @@ Example:
alert("Selected value is: "+$("#e8").select2("
 

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.

@@ -1696,7 +1719,7 @@ Example:
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.

@@ -1704,14 +1727,14 @@ Example:
alert("Selected value is: "+$("#e8").select2("
 

select2-focus

-

Fired when the control is focussed +

Fired when the control is focussed.

select2-blur

-

Fired when the control is blurred +

Fired when the control is blurred.

@@ -1720,8 +1743,7 @@ Example:
alert("Selected value is: "+$("#e8").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.
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({

-

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 the select, or via the placeholder configuration element as seen in the example code

+

The placeholder can be declared via a data-placeholder attribute attached to the select, or via the placeholder 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 alternative transport function can be specified in the ajax settings, or an entirely custom implementation can be built by providing a custom query function instead of using the ajax helper

+

Select2 uses jQuery's $.ajax function to execute the remote call by default. An alternative transport function can be specified in the ajax settings, or an entirely custom implementation can be built by providing a custom query function instead of using the ajax helper.

@@ -612,7 +612,7 @@ $("#e8_2_close").click(function () { $("#e8_2").select2("close"); });

Programmatic Access

-

Select2 supports methods that allow programmatic control of the component

+

Select2 supports methods that allow programmatic control of the component:

@@ -691,7 +691,7 @@ $("#e11_2")

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:

@@ -714,7 +714,7 @@ $("#e11_2")

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 @@ -762,10 +762,10 @@ $("#e11_2")

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.

@@ -902,15 +902,15 @@ $("#e17_2").select2({

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

-
-           
+
+
@@ -1074,13 +1074,13 @@ $(document).ready(function () {
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.
- minimumInputLengthintNumber of characters necessary to start a search - maximumInputLengthintMaximum number of characters that can be entered for an input + minimumInputLengthintNumber of characters necessary to start a search. + maximumInputLengthintMaximum number of characters that can be entered for an input. minimumResultsForSearchint

The minimum number of results that must be initially (after opening the dropdown for the first time) @@ -1088,7 +1088,7 @@ $(document).ready(function () { 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

@@ -1097,7 +1097,7 @@ $(document).ready(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

+ by the formatSelectionTooBig function.

placeholderstring @@ -1134,7 +1134,7 @@ $(document).ready(function () { only available when the placeholder is specified.

-

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.

@@ -1184,8 +1184,8 @@ $(document).ready(function () {
id(object)
- - + +
ParameterTypeDescription
objectobjectA choice object
<returns>stringthe id of the object
objectobjectA choice object.
<returns>stringthe id of the object.
The default implementation expects the object to have a id property that is returned. @@ -1195,12 +1195,12 @@ $(document).ready(function () {
matcher(term, text, option)
- - + + - +
ParameterTypeDescription
termstringsearch term
textstringtext of the option being matched
termstringsearch term.
textstringtext of the option being matched.
optionjquery 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>booleantrue if search term matches the text, or false otherwise
<returns>booleantrue 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; } @@ -1209,9 +1209,9 @@ $(document).ready(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)
- - - + . + +
objectobjectOne of the result objects returned from the query function
containerjQuery objectjQuery wrapper of the node that should contain the representation of the result
queryobjectThe query object used to request this set of results
objectobjectOne of the result objects returned from the query function
containerjQuery objectjQuery wrapper of the node that should contain the representation of the result.
queryobjectThe query object used to request this set of results.
<returns>objectA results object.
Defaults to no sorting: @@ -1222,22 +1222,22 @@ $(document).ready(function () {
formatSelection(object, container)
- - + + - +
ParameterTypeDescription
objectobjectThe selected result object returned from the query function
containerjQuery objectjQuery wrapper of the node to which the selection should be appended
objectobjectThe selected result object returned from the query function.
containerjQuery objectjQuery wrapper of the node to which the selection should be appended.
escapeMarkupfunctionFunction that can be used to escape html markup. This is the function defined in the escapeMarkupoption, 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
+}
+

formatResultfunction @@ -1245,70 +1245,70 @@ $(document).ready(function () {
formatResult(object, container, query)
- - - + + + - +
ParameterTypeDescription
objectobjectOne of the result objects returned from the query function
containerjQuery objectjQuery wrapper of the node that should contain the representation of the result
queryobjectThe query object used to request this set of results
objectobjectOne of the result objects returned from the query function.
containerjQuery objectjQuery wrapper of the node that should contain the representation of the result.
queryobjectThe query object used to request this set of results.
escapeMarkupfunctionFunction 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
+}
+

formatResultCssClassfunction - Function used to add css classes to result elements + Function used to add css classes to result elements.
formatResultCssClass(object)
- - + +
ParameterTypeDescription
objectobjectOne of the result objects returned from the query function
<returns>string (optional)String containing css class names separated by a space
objectobjectOne 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 options will be automatically copied

+

By default when attached to a select css classes from options will be automatically copied.

formatNoMatchesfunction Function used to render the "No matches" message
formatNoMatches(term)
- - + +
ParameterTypeDescription
termstringSearch string entered by user
<returns>stringMessage html
termstringSearch string entered by user.
<returns>stringMessage html.
formatSearchingfunction Function used to render the "Searching..." message that is displayed while - search is in progress + search is in progress.
formatSearching()
- +
ParameterTypeDescription
<returns>stringMessage html or null/undefined to disable the message
<returns>stringMessage html or null/undefined to disable the message.
formatInputTooShortfunction - Function used to render the "Search input too short" message + Function used to render the "Search input too short" message.
formatInputTooShort(term, minLength)
- - - + + +
ParameterTypeDescription
termstringSearch string entered by user
minLengthintMinimum required term length
<returns>stringMessage html
termstringSearch string entered by user.
minLengthintMinimum required term length.
<returns>stringMessage html.
formatSelectionTooBigfunction - Function used to render the "You cannot select any more choices" message + Function used to render the "You cannot select any more choices" message.
formatSelectionTooBig(maxSize)
- - + +
ParameterTypeDescription
maxSizestringThe maximum specified size of the selection
<returns>stringMessage html
maxSizestringThe maximum specified size of the selection.
<returns>stringMessage html.
createSearchChoicefunction @@ -1317,7 +1317,7 @@ $(document).ready(function () {
createSearchChoice(term)
- +
ParameterTypeDescription
termstringSearch string entered by user
termstringSearch string entered by user.
<returns>object (optional)Object representing the new choice. Must at least contain an id attribute.
@@ -1327,7 +1327,7 @@ $(document).ready(function () {

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.

initSelectionfunction Called when Select2 is created to allow the user to initialize the selection based on the value of the @@ -1338,8 +1338,8 @@ $(document).ready(function () {
initSelection(element, callback)
- - + +
ParameterTypeDescription
elementjQuery arrayelement Select2 is attached to
callbackfunctioncallback 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
elementjQuery arrayelement Select2 is attached to.
callbackfunctioncallback 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 @@ -1368,14 +1368,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)
- + - + @@ -1402,16 +1402,16 @@ $("#select").select2({
query(options)
ParameterTypeDescription
inputstringThe text entered into the search field so far
inputstringThe text entered into the search field so far.
selectionarrayArray of objects representing the current selection. Useful if tokenizer needs to filter out duplicates.
selectCallbackfunctionCallback that can be used to add objects to the selection
selectCallbackfunctionCallback that can be used to add objects to the selection.
optsobjectOptions 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 @@ -1391,7 +1391,7 @@ $("#select").select2({
tokenSeparatorsarray 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 [',', ' '].
- - - + + + @@ -1456,19 +1456,19 @@ $("#select").select2({ - - - + + +
ParameterTypeDescription
options.elementjquery objectThe element Select2 is attached to
options.termstringSearch string entered by user
options.pageint1-based page number tracked by Select2 for use with infinite scrolling of results
options.elementjquery objectThe element Select2 is attached to.
options.termstringSearch string entered by user.
options.pageint1-based page number tracked by Select2 for use with infinite scrolling of results.
options.contextobjectAn 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.callbackfunction Callback function that should be called with the result object. The result object: - +
ParameterTypeDescription
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 childrenkey if hierarchical data is displayed.
result.morebooleantrueif more results are available for the current search term
result.morebooleantrueif more results are available for the current search term.
results.contextobjectA 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.
transportfunctionFunction 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.
urlstring/functionString containing the ajax url or a function that returns such a string.
dataTypestringData type for the request. xml, json, jsonp, other formats supported by jquery
quietMillisintNumber of milliseconds to wait for the user to stop typing before issuing the ajax request
cachebooleanIf set to false, it will force requested pages not to be cached by the browser. Default is false
dataTypestringData type for the request. xml, json, jsonp, other formats supported by jquery.
quietMillisintNumber of milliseconds to wait for the user to stop typing before issuing the ajax request.
cachebooleanIf set to false, it will force requested pages not to be cached by the browser. Default is false.
jsonpCallbackstring/functionThe 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.
datafunction Function to generate query parameters for the ajax request.
data(term, page)
- - + + - +
ParameterTypeDescription
termstringSearch term
pageint1-based page number tracked by Select2 for use with infinite scrolling of results
termstringSearch term.
pageint1-based page number tracked by Select2 for use with infinite scrolling of results.
contextobjectSee options.context parameter to the query function above.
<returns>objectObject containing url paramters
<returns>objectObject containing url parameters.
resultsfunction @@ -1476,8 +1476,8 @@ $("#select").select2({
results(data, page)
- - + +
ParameterTypeDescription
dataobjectRetrieved data
pageintPage number that was passed into the data function above
dataobjectRetrieved data.
pageintPage number that was passed into the data function above.
contextobjectSee options.context parameter to the query function above.
<returns>objectResults object. See "options.callback" in the "query" function for format.
@@ -1486,12 +1486,12 @@ $("#select").select2({

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.

dataarray/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

+

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.

tagsarray/function Puts Select2 into 'tagging'mode where the user can add new choices and pre-existing tags are provided via @@ -1504,13 +1504,13 @@ $("#select").select2({ 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. containerCssClassfunction/string - Css class that will be added to select2's container tag + Css class that will be added to select2's container tag. dropdownCssfunction/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. dropdownCssClassfunction/string - Css class that will be added to select2's dropdown container + Css class that will be added to select2's dropdown container. dropdownAutoWidthboolean When set to true attempts to automatically size the width of the dropdown based on content inside. @@ -1520,8 +1520,8 @@ $("#select").select2({
adaptContainerCssClass(clazz)
- - + +
ParameterTypeDescription
clazzstringCss class being copied
<returns>stringCss class to be applied or null/undefined/'' to not apply it
clazzstringCss class being copied.
<returns>stringCss class to be applied or null/undefined/'' to not apply it.
The default implementation applies all classes without modification. @@ -1530,8 +1530,8 @@ $("#select").select2({
adaptDropdownCssClass(clazz)
- - + +
ParameterTypeDescription
clazzstringCss class being copied
<returns>stringCss class to be applied or null/undefined/'' to not apply it
clazzstringCss class being copied.
<returns>stringCss class to be applied or null/undefined/'' to not apply it.
The default implementation always returns null thereby filtering out all classes. @@ -1540,12 +1540,32 @@ $("#select").select2({

Function used to post-process markup returned from formatter functions. By default this function escapes html entities to prevent javascript injection.

selectOnBlurboolean -

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.

loadMorePaddinginteger Defines how many pixels 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. - + nextSearchTermfunction +

Function used to determine what the next search term should be.

+ + + + + + +
ParameterTypeDescription
dataobjectRetrieved data.
this.search.val()stringSearch 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.

+
@@ -1564,7 +1584,7 @@ $("#select").select2({ Attached to select - Value of the value attribute of the option that should be selected + Value of the value attribute of the option that should be selected. Array of the value attributes of the options that should be selected. null for empty. @@ -1577,7 +1597,7 @@ $("#select").select2({ triggerChange (optional)booleanWhether or not a 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 [].

Example:
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.

@@ -1586,7 +1606,7 @@ $("#select").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 [].

@@ -1597,11 +1617,11 @@ $("#select").select2({

open

-

Opens the dropdown

+

Opens the dropdown.

close

-

Closes the dropdown

+

Closes the dropdown.

enable(boolean)

@@ -1639,9 +1659,9 @@ $("#select").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.

@@ -1668,8 +1688,8 @@ $("#select").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.

@@ -1682,8 +1702,8 @@ $("#select").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.

@@ -1691,12 +1711,12 @@ $("#select").select2({

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.

@@ -1708,7 +1728,7 @@ $("#select").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.

@@ -1716,14 +1736,14 @@ $("#select").select2({

select2-focus

-

Fired when the control is focussed +

Fired when the control is focussed.

select2-blur

-

Fired when the control is blurred +

Fired when the control is blurred.

@@ -1732,7 +1752,7 @@ $("#select").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.