diff --git a/index.html b/index.html index caac38b2..edea33d2 100644 --- a/index.html +++ b/index.html @@ -2,63 +2,64 @@ layout: main title: Select2 group: navigation -version: 3.4.0 +version: 3.4.1 +milestone: 11 --- - - + + -
- +
@@ -236,7 +237,7 @@ $("#e10_4").select2({
  • Loading...
  • -
    -

    Placeholders

    -

    A placeholder value can be defined and will be displayed until a selection is made:

    -

    -
    -

    -

    -
    -

    -

    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

    -

    Optionally, a clear button (visible once a selection is made) is available to reset the select box back to the placeholder value.

    + $("#e2_2").select2({ + placeholder: "Select a State" + }); + }); + +
    +

    Placeholders

    +

    A placeholder value can be defined and will be displayed until a selection is made:

    +

    +
    +

    +

    +
    +

    +

    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

    +

    Optionally, a clear button (visible once a selection is made) is available to reset the select box back to the placeholder value.

    -
    -
    -

    Example Code

    +
    +
    +

    Example Code

                 
    -
    - +
    + -
    -
    -

    Minimum Input

    -

    Select2 supports a minimum input setting which is useful for large remote datasets where short search terms are not very useful:

    -

    -
    -

    -
    -
    -

    Example Code

    -
    
    -         
    -
    +
    +
    +

    Minimum Input

    +

    Select2 supports a minimum input setting which is useful for large remote datasets where short search terms are not very useful:

    +

    +
    +

    +
    +
    +

    Example Code

    +
    
    +    
    +
    -
    -
    -

    Templating

    -

    Various display options of the Select2 component can be changed:

    -

    -
    -

    -
    -
    -

    Example Code

    -
    
    -            

    - You can set data- attributes to <option> (or <optgroup>) and use them inside temptlating functions: -

    +
    +
    +

    Templating

    +

    Various display options of the Select2 component can be changed:

    +

    +
    +

    +
    +
    +

    Example Code

    +
    
    +        

    + You can set data- attributes to <option> (or <optgroup>) and use them inside temptlating functions: +

     <select>
         <option value="0" data-foo="bar">option one</option>
    @@ -475,836 +475,834 @@ function format(state) {
         return "<img class='flag' src='images/flags/" + state.id.toLowerCase() + ".png' alt='" + $(originalOption).data('foo') + "' />" + state.text;
     }
                 
    -
    -
    +
    +
    -
    -
    -

    Loading Data

    -

    Select2 uses a function to load result data. Here is a trivial example that creates choices that consist of user's input repeated a number of times:

    -

    - -

    -

    In order to take advantage of custom data loading Select2 should be attached to an input type='hidden' tag, otherwise data is parsed from select's option tags.

    -
    -
    -

    Example Code

    +
    +
    +

    Loading Data

    +

    Select2 uses a function to load result data. Here is a trivial example that creates choices that consist of user's input repeated a number of times:

    +

    + +

    +

    In order to take advantage of custom data loading Select2 should be attached to an input type='hidden' tag, otherwise data is parsed from select's option tags.

    +
    +
    +

    Example Code

                 
    -
    -
    +
    +
    -
    -
    -

    Maximum Selection Size

    -

    Select2 allows the developer to limit the number of items that can be selected in a multi-select control. - In the example below only 3 or less items can be selected.

    -

    - -

    -
    -
    -

    Example Code

    +
    +
    +

    Maximum Selection Size

    +

    Select2 allows the developer to limit the number of items that can be selected in a multi-select control. + In the example below only 3 or less items can be selected.

    +

    + +

    +
    +
    +

    Example Code

                 
    -
    -
    +
    +
    -
    -
    -

    Loading Array Data

    -

    Select2 provides some shortcuts that make it easy to access local data stored in an array instead of having to write a query function mentioned in the example above.

    -

    Example below inlines the data by specifying an array in the data element. Items in such an array must have id and text keys.

    -

    - -

    -

    If your data does not have a text key, an alternative key can be specified as a string:

    -

    - -

    -

    or as a function:

    -

    - -

    -

    data can also itself be a function that returns a results object:

    -

    - -

    +
    +
    +

    Loading Array Data

    +

    Select2 provides some shortcuts that make it easy to access local data stored in an array instead of having to write a query function mentioned in the example above.

    +

    Example below inlines the data by specifying an array in the data element. Items in such an array must have id and text keys.

    +

    + +

    +

    If your data does not have a text key, an alternative key can be specified as a string:

    +

    + +

    +

    or as a function:

    +

    + +

    +

    data can also itself be a function that returns a results object:

    +

    + +

    -
    -
    -

    Example Code

    +
    +
    +

    Example Code

                
    -
    -
    +
    +
    -
    -
    -

    Loading Remote Data

    -

    Select2 comes with AJAX/JSONP support built in. In this example we will search for a movie using Rotten Tomatoes API:

    -

    - -

    -

    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

    -
    -
    -
    -
    -

    Infinite Scroll with Remote Data

    -

    Select2 supports lazy-appending of results when the result list is scrolled to the end. - In order to enable the remote service must support some sort of a paging mechanism and - the query function given to Select2 must take advantage of it. The following example demonstrates - how this can be set up. Search for some keyword and then scroll the result list to the end to - see more results load:

    -

    - -

    -

    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

    -
    
    -            
    -
    +
    +
    +

    Loading Remote Data

    +

    Select2 comes with AJAX/JSONP support built in. In this example we will search for a movie using Rotten Tomatoes API:

    +

    + +

    +

    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

    +
    +
    +
    +
    +

    Infinite Scroll with Remote Data

    +

    Select2 supports lazy-appending of results when the result list is scrolled to the end. + In order to enable the remote service must support some sort of a paging mechanism and + the query function given to Select2 must take advantage of it. The following example demonstrates + how this can be set up. Search for some keyword and then scroll the result list to the end to + see more results load:

    +

    + +

    +

    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

    +
    
    +    
    +
    -
    - -
    -

    Programmatic Access

    -

    Select2 supports methods that allow programmatic control of the component

    -

    - - - - - - - -

    -

    -
    -

    -

    - - - - - - - -

    -

    -
    -

    -
    -
    -

    Example Code

    -
    
    -         
    -
    +
    + +
    +

    Programmatic Access

    +

    Select2 supports methods that allow programmatic control of the component

    +

    + + + + + + + +

    +

    +
    +

    +

    + + + + + + + +

    +

    +
    +

    +
    +
    +

    Example Code

    +
    
    +    
    +
    -
    - -
    -

    Events

    +
    + +
    +

    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

    +

    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

    -

    -

    +

    +

    -
    -
    -

    Event Log

    -
      -

      Example Code

      +
      +
      +

      Event Log

      +
        +

        Example Code

                    
        -
        -
        -
        - -
        -

        Tagging Support

        +
        +
        +
        + +
        +

        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 - picking the first choice which is what the user has typed into the search box so far.

        -
        -
        -

        Example Code

        +

        +

        Note that when tagging is enabled the user can select from pre-existing tags or create a new tag by + picking the first choice which is what the user has typed into the search box so far.

        +
        +
        +

        Example Code

                    
        -
        -
        -
        - -
        -

        Maximum Input Length

        +
        +
        +
        + +
        +

        Maximum Input Length

        -

        Select2 can be set a limit on the number of characters that can be entered per tag.

        +

        Select2 can be set a limit on the number of characters that can be entered per tag.

        -

        -

        You would not be able to enter any input of more than 10 characters long.

        -
        -
        -

        Example Code

        +

        +

        You would not be able to enter any input of more than 10 characters long.

        +
        +
        +

        Example Code

                    
        -
        -
        -
        - -
        -

        Auto Tokenization

        +
        +
        +
        + +
        +

        Auto Tokenization

        -

        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

        +

        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

        -

        -

        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.

        -
        -
        -

        Example Code

        +

        +

        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.

        +
        +
        +

        Example Code

                    
        -
        -
        -
        - -
        -

        Reacting to external value changes

        +
        +
        +
        + +
        +

        Reacting to external value changes

        -

        Select2 can react to external value changes and keep its selection in-sync. This feature allows - Select2 to work seamlessly with front-end frameworks that use data binding between ui components - and model values.

        -


        -

        -

        This feature is only available when initSelection() function is provided in - the options. This function is needed to map the choice ids set on the element to objects used by - Select2. This function is set by default when Select2 is attached to a select or when - the tags helper function is used.

        -
        -
        -

        Example Code

        +

        Select2 can react to external value changes and keep its selection in-sync. This feature allows + Select2 to work seamlessly with front-end frameworks that use data binding between ui components + and model values.

        +


        +

        +

        This feature is only available when initSelection() function is provided in + the options. This function is needed to map the choice ids set on the element to objects used by + Select2. This function is set by default when Select2 is attached to a select or when + the tags helper function is used.

        +
        +
        +

        Example Code

                    
        -
        -
        +
        +
        -
        - -
        -

        Select2 Lifecycle

        +
        + +
        +

        Select2 Lifecycle

        -

        +

        -

        -


        -

        -
        -
        -

        Example Code

        +

        +


        +

        +
        +
        +

        Example Code

                    
        -
        -
        +
        +
        -
        - -
        -

        Select2 Drag and Drop Sorting

        -

        - Select2 supports drag and drop sorting of selected choices. Select2 does not, itself, provide the necessary code to perform dragging and dropping, instead it provides hooks that other libraries can use to provide the behavior. In this example we are using JQuery UI's sortable() plugin. -

        -

        The sorting is only available when Select2 is attached to a hidden input field.

        -

        -

        -
        -
        -

        Example Code

        + $("#e15").select2("container").find("ul.select2-choices").sortable({ + containment: 'parent', + start: function() { $("#e15").select2("onSortStart"); }, + update: function() { $("#e15").select2("onSortEnd"); } + }); + }); + +
        +

        Select2 Drag and Drop Sorting

        +

        + Select2 supports drag and drop sorting of selected choices. Select2 does not, itself, provide the necessary code to perform dragging and dropping, instead it provides hooks that other libraries can use to provide the behavior. In this example we are using JQuery UI's sortable() plugin. +

        +

        The sorting is only available when Select2 is attached to a hidden input field.

        +

        +

        +
        +
        +

        Example Code

                    
        -
        -
        + + -
        - -
        -

        Select2 Disabled Mode

        -


        -


        -

        -

        -
        -
        -

        Example Code

        + }); + +
        +

        Select2 Disabled Mode

        +


        +


        +

        +

        +
        +
        +

        Example Code

                    
        -
        -
        + + -
        - -
        -

        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

        -


        -

        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

        -
        -           
        -
        -
        - -
        - -
        -

        Sorting Displayed Results

        -

        Unlike other dropdowns on this page, this one filters results by query string normally, but returns the matched results sorted from shortest to longest by string length. Try typing 'e' and seeing how the results are sorted. This function is useful for sorting results by relevance to a user's query.

        -

        -
        -

        -
        -
        -

        Example Code

        + }); + +
        +

        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

        +


        +

        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

        +
        +           
        +
        +
        + +
        + +
        +

        Sorting Displayed Results

        +

        Unlike other dropdowns on this page, this one filters results by query string normally, but returns the matched results sorted from shortest to longest by string length. Try typing 'e' and seeing how the results are sorted. This function is useful for sorting results by relevance to a user's query.

        +

        +
        +

        +
        +
        +

        Example Code

                     
        -
        -
        + + -
        - -
        -

        Responsive Design - Percent Width

        -

        Select2's width can be set to a percentage of its parent to support responsive design. The two Select2 boxes below are styled to 50% and 75% width respectively.

        -


        -


        -

        Select2 will do its best to resolve the percent width specified via a css class, but it is not always possible. The best way to ensure that Select2 is using a percent based width is to inline the style declaration into the tag.

        -
        -
        -

        Example Code

        +
        + +
        +

        Responsive Design - Percent Width

        +

        Select2's width can be set to a percentage of its parent to support responsive design. The two Select2 boxes below are styled to 50% and 75% width respectively.

        +


        +


        +

        Select2 will do its best to resolve the percent width specified via a css class, but it is not always possible. The best way to ensure that Select2 is using a percent based width is to inline the style declaration into the tag.

        +
        +
        +

        Example Code

                    
        -
        -
        +
        +
        -
        - -
        -

        Lock selections

        -

        - In the event that you need to lock certain selections so that they can't be removed by the select2 interface, you can now pass in locked: true with your data. Please note: This also works for incoming values from ajax. -

        -

        - -

        -
        -
        -

        Example Code

        + query.callback(data); + } + }); + $('#e21').select2('data', preload_data ) + }); + +
        +

        Lock selections

        +

        + In the event that you need to lock certain selections so that they can't be removed by the select2 interface, you can now pass in locked: true with your data. Please note: This also works for incoming values from ajax. +

        +

        + +

        +
        +
        +

        Example Code

                 
        -
        -
        + + -
        + - - - + + + -
        +
        -
        -

        Documentation


        -
        +
        +

        Documentation


        +
        -
        -

        Constructor

        -
        - - - - - - - - - - - -
        ParameterTypeDescription
        widthstring - 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 evaluated, 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
        minimumResultsForSearchint -

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

        -

        The option can be set to a negative value to permanently hide the search field

        -

        Only applies to single-value select boxes

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

        -
        placeholderstring -

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

        +
        +

        Constructor

        +
        + + + + + + + + + + + + - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + - - - - - - - - - - + + + + + + + + + + - + - - - - - - - + + + + + + - + - + - + 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. + + - - - - + + + +

        + + + + + + + + + + + + + + + + +
        ParameterTypeDescription
        widthstring + 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
        +
        +
        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) + 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. +

        +

        The option can be set to a negative value to permanently hide the search field

        +

        Only applies to single-value select boxes

        +
        maximumSelectionSizeint/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

        +
        placeholderstring +

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

        -
        separatorstring -

        - Separator character or string used to delimit ids in value attribute of the multi-valued selects. - The default delimiter is the , character. -

        -
        allowClearboolean -

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

        -
        multipleboolean -

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

        -
        closeOnSelectboolean -

        - If set to false the dropdown is not closed after a selection is made, allowing for rapid selection of multiple items. By default this option is set to true. -

        +

        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. +

        +
        placeholderOptionfunction/string +

        When attached to a select resolves the option that should be used as the placeholder. + Can either be a function which given the select element should return the optoin + element or a string first to indicate that the first option should be used.

        +

        This option is useful when Select2's default of using the first option only if it has no value and no text is not suitable.

        +
        separatorstring +

        + Separator character or string used to delimit ids in value attribute of the multi-valued selects. + The default delimiter is the , character. +

        +
        allowClearboolean +

        + 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. +

        +
        multipleboolean +

        + 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. +

        +
        closeOnSelectboolean +

        + If set to false the dropdown is not closed after a selection is made, allowing for rapid selection of multiple items. By default this option is set to true. +

        -

        - Only applies when configured in multi-select mode. -

        -
        openOnEnterboolean -

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

        -
        idfunction - Function used to get the id from the choice object or a string representing the key under which the id is stored. -
        id(object)
        - - - - -
        ParameterTypeDescription
        objectobjectA choice object
        <returns>stringthe id of the object
        - The default implementation expects the object to have a id property that is returned. -
        matcherfunction - 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)
        - - - - - - - -
        ParameterTypeDescription
        termstringsearch term
        textstringtext of the option being matched
        optionjquery objectthe 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
        - The default implementation is case insensitive and matches anywhere in the term: - function(term, text) { return text.toUpperCase().indexOf(term.toUpperCase())>=0; } -
        sortResultsfunction - 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
        <returns>objectA results object.
        - Defaults to no sorting: - function(results, container, query) { return results; } -
        formatSelectionfunction - Function used to render the current selection. -
        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
        <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: +

        + Only applies when configured in multi-select mode. +

        +
        openOnEnterboolean +

        + 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. +

        +
        idfunction + Function used to get the id from the choice object or a string representing the key under which the id is stored. +
        id(object)
        + + + + +
        ParameterTypeDescription
        objectobjectA choice object
        <returns>stringthe id of the object
        + The default implementation expects the object to have a id property that is returned. +
        matcherfunction + 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)
        + + + + + + + +
        ParameterTypeDescription
        termstringsearch term
        textstringtext of the option being matched
        optionjquery objectthe 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
        + The default implementation is case insensitive and matches anywhere in the term: + function(term, text) { return text.toUpperCase().indexOf(term.toUpperCase())>=0; } +
        sortResultsfunction + 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
        <returns>objectA results object.
        + Defaults to no sorting: + function(results, container, query) { return results; } +
        formatSelectionfunction + Function used to render the current selection. +
        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
        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
        +

        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
                             }
                         
        -

        -
        formatResultfunction - Function used to render a result that the user can select. -
        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
        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
        -

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

        +
        formatResultfunction + Function used to render a result that the user can select. +
        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
        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
        +

        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
                             }
                         
        -

        -
        formatResultCssClassfunction - 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
        -

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

        -
        formatSelectionCssClassfunction - Function used to add css classes to selected elements -
        formatSelectionCssClass(object)
        - - - - -
        ParameterTypeDescription
        objectobjectOne of the result objects returned from the query function
        <returns>string (optional)String containing css class names separated by a space
        -
        formatNoMatchesfunction - Function used to render the "No matches" message -
        formatNoMatches(term)
        - - - - -
        ParameterTypeDescription
        termstringSearch string entered by user
        <returns>stringMessage html
        -
        formatSearchingfunction - Function used to render the "Searching..." message that is displayed while - search is in progress -
        formatSearching()
        - - - -
        ParameterTypeDescription
        <returns>stringMessage html or null/undefined to disable the message
        -
        formatInputTooShortfunction - 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
        -
        formatSelectionTooBigfunction - 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
        -
        createSearchChoicefunction - 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)
        - - - - -
        ParameterTypeDescription
        termstringSearch 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. +

        +
        formatResultCssClassfunction + 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
        +

        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
        +
        formatSearchingfunction + Function used to render the "Searching..." message that is displayed while + search is in progress +
        formatSearching()
        + + + +
        ParameterTypeDescription
        <returns>stringMessage html or null/undefined to disable the message
        +
        formatInputTooShortfunction + 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
        +
        formatSelectionTooBigfunction + 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
        +
        createSearchChoicefunction + 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)
        + + + + +
        ParameterTypeDescription
        termstringSearch 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

        -
        initSelectionfunction - 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)
        - - - - -
        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
        -

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

        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

        +
        initSelectionfunction + 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)
        + + + + +
        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
        +

        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) {
        @@ -1324,62 +1322,62 @@ $("#select").select2({
             }
         });
         
        -
        tokenizerfunction - 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)
        - - - - - - - -
        ParameterTypeDescription
        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
        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 - the tokens have been stripped. If undefined or null is returned the - input of the search field is unchanged.
        +
        tokenizerfunction + 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)
        + + + + + + + +
        ParameterTypeDescription
        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
        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 + 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. -
        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 [',', ' '] -
        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 [',', ' '] +
        queryfunction - Function used to query results for the search term. -
        query(options)
        +
        queryfunction + Function used to query results for the search term. +
        query(options)
        + + + + + + + + +
        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.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.callbackfunctionCallback function that should be called with the result object. The result object: - - - - - - + + +
        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.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.callbackfunctionCallback 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
        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.
        -
        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
        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.
        -

        In order for this function to work Select2 should be attached to a input type='hidden' tag instead of a select.

        -

        -

        Example Data

        +
        +

        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,
        @@ -1389,9 +1387,9 @@ $("#select").select2({
              ]
         }
                                 
        -

        -

        -

        Example Hierarchical Data

        +

        +

        +

        Example Hierarchical Data

         {
             more: false,
        @@ -1406,302 +1404,297 @@ $("#select").select2({
             ]
         }
                                 
        -

        -
        ajaxobject + 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. + + + + + + + + + + + + + +
        ParameterTypeDescription
        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. ajax, 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
        contextobjectSee options.context parameter to the query function above.
        <returns>objectObject containing url paramters
        +
        resultsfunction + Function used to build the query results object from the ajax response +
        results(data, page)
        + + + + + + +
        ParameterTypeDescription
        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.
        +
        paramsobject/functionAn 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.

        +

        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

        +
        tagsarray/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. +
        containerCssfunction/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. +
        containerCssClassfunction/string + 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 +
        dropdownAutoWidthboolean + When set to true attempts to automatically size the width of the dropdown based on content inside. +
        adaptContainerCssClassfunction + Function that filters/renames css classes as they are copied from the source tag to the select2 container tag. +
        adaptContainerCssClass(clazz)
        + + + + +
        ParameterTypeDescription
        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. +
        adaptDropdownCssClassfunction + Function that filters/renames css classes as they are copied from the source tag to the select2 dropdown tag. +
        adaptDropdownCssClass(clazz)
        + + + + +
        ParameterTypeDescription
        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. +
        escapeMarkupfunction + 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.

        +
        selectOnBlurboolean +

        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. +
        + +
        +

        val

        +
        +

        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.

        + + + + + + +
        ParameterTypeDescription
        value (optional)object + + + + + + + + + + + + + + - - - - - - - - - - - - -
        Single-ValuedMulti-Valued
        Attached to selectValue of the value attribute of the option that should be selectedArray of the value attributes of the options that should be selected. null for empty.
        Attached to input[type=hidden]Id of the object that should be selected. "" to clear. Can only be used if initSelection() was specified.An array of objects ids that should be selected. "" to clear. Can only be used if initSelection() was specified.
        ajaxobject - 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. - - - - - - - - - - - - - -
        ParameterTypeDescription
        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. ajax, 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
        contextobjectSee options.context parameter to the query function above.
        <returns>objectObject containing url paramters
        -
        resultsfunction - Function used to build the query results object from the ajax response -
        results(data, page)
        - - - - - - -
        ParameterTypeDescription
        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.
        -
        paramsobject/functionAn 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.

        -

        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

        -
        tagsarray/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. -
        containerCssfunction/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. -
        containerCssClassfunction/string - 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 -
        dropdownAutoWidthboolean - When set to true attempts to automatically size the width of the dropdown based on content inside. -
        adaptContainerCssClassfunction - Function that filters/renames css classes as they are copied from the source tag to the select2 container tag. -
        adaptContainerCssClass(clazz)
        - - - - -
        ParameterTypeDescription
        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. -
        adaptDropdownCssClassfunction - Function that filters/renames css classes as they are copied from the source tag to the select2 dropdown tag. -
        adaptDropdownCssClass(clazz)
        - - - - -
        ParameterTypeDescription
        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. -
        escapeMarkupfunction - 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.

        -
        selectOnBlurboolean -

        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. -
        +
        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

        -
        -

        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.

        - - - - - - -
        ParameterTypeDescription
        value (optional)object +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.

        - - - - - - - - - - - - - - - -
        Single-ValuedMulti-Valued
        Attached to selectValue of the value attribute of the option that should be selectedArray of the value attributes of the options that should be selected. null for empty.
        Attached to input[type=hidden]Id of the object that should be selected. "" to clear. Can only be used if initSelection() was specified.An array of objects ids that should be selected. "" to clear. Can only be used if initSelection() was specified.
        -
        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 []

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

        - -
        -

        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

        +
        +

        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 []

        -
        -

        destroy

        -
        -

        Reverts changes to DOM done by Select2. Any selection done via Select2 will be preserved.

        +
        +

        destroy

        +
        +

        Reverts changes to DOM done by Select2. Any selection done via Select2 will be preserved.

        -
        -

        open

        -
        -

        Opens the dropdown

        -
        -

        close

        -
        -

        Closes the dropdown

        -
        -

        search

        -
        -

        Opens the dropdown, sets the value of the input, and updates the results list. - Example: $("#tags").select2("search", "foo");

        -
        -

        enable(boolean)

        -
        -

        Enables or disables Select2 and its underlying form component based on the boolean parameter.

        -
        -

        readonly(boolean)

        -
        -

        Toggles readonly mode on Select2 and its underlying form component based on the boolean parameter.

        +
        +

        open

        +
        +

        Opens the dropdown

        +
        +

        close

        +
        +

        Closes the dropdown

        +
        +

        enable(boolean)

        +
        +

        Enables or disables Select2 and its underlying form component based on the boolean parameter.

        +
        +

        readonly(boolean)

        +
        +

        Toggles readonly mode on Select2 and its underlying form component based on the boolean parameter.

        -
        +

        container

        +
        +

        Retrieves the main container element that wraps all of DOM added by Select2 + Example: console.log($("#tags").select2("container"));

        +
        +

        onSortStart

        +
        +

        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");

        +
        +

        onSortEnd

        +
        +

        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"); +

        + + +
        +

        Events

        +
        + +
        +
        +

        change

        +

        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
        +
        +

        -

        Retrieves the main container element that wraps all of DOM added by Select2 - Example: console.log($("#tags").select2("container"));

        -
        -

        onSortStart

        +
        +
        +
        +

        select2-opening

        +

        Fired before the dropdown is shown.

        +

        The event listener can prevent the opening by calling preventDefault() on the supplied event object.

        +

        -

        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");

        -
        -

        onSortEnd

        +
        +
        +
        +

        select2-open

        +

        Fired after the dropdown is shown.

        +

        -

        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"); -

        - - -
        -

        Events

        -
        - -
        -
        -

        change

        -

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

        -
        -
        -
        -
        -

        select2-opening

        -

        Fired before the dropdown is shown.

        -

        The event listener can prevent the opening by calling preventDefault() on the supplied event object.

        -

        -
        -
        -
        -
        -

        select2-open

        -

        Fired after the dropdown is shown.

        -

        -
        -
        -
        -
        -

        select2-highlight

        -

        Fired when a choice is highlighted in the dropdown.

        -

        -

        The event object contains the following custom properties: -

        -
        val
        the id of the highlighted choice object
        -
        object
        the highlighted choice object
        -
        -

        -
        -
        -
        -
        -

        select2-selecting

        -

        Fired when a choice is being selected in the dropdown, but before any modification has been made to the selection. - This event is used to allow the user to reject selection by calling event.preventDefault()

        -

        -

        The event object contains the following custom properties: -

        -
        val
        the id of the highlighted choice object
        -
        object
        the choice object about to be selected
        -
        -

        -
        -
        -
        -
        -

        select2-removed

        -

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

        -
        -
        -
        -
        -

        select2-loaded

        -

        Fired when query function is done loading the data and the results list has been updated

        -

        -

        The event object contains the following custom properties: -

        -
        data
        data that was used to populate the results
        -
        -

        -
        -
        -
        -
        -

        select2-focus

        -

        Fired when the control is focussed -

        -
        -
        -
        -
        -

        select2-blur

        -

        Fired when the control is blurred -

        -
        -
        - - -
        -
        -

        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-highlight

        +

        Fired when a choice is highlighted in the dropdown.

        +

        +

        The event object contains the following custom properties: +

        +
        val
        the id of the highlighted choice object
        +
        object
        the highlighted choice object
        +
        +

        +
        +
        +
        +

        select2-selecting

        +

        Fired when a choice is being selected in the dropdown, but before any modification has been made to the selection. + This event is used to allow the user to reject selection by calling event.preventDefault()

        +

        +

        The event object contains the following custom properties: +

        +
        val
        the id of the highlighted choice object
        +
        object
        the choice object about to be selected
        +
        +

        +
        +
        +
        +
        +

        select2-removed

        +

        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
        +
        +

        +
        +
        +
        +
        +

        select2-loaded

        +

        Fired when query function is done loading the data and the results list has been updated

        +

        +

        The event object contains the following custom properties: +

        +
        items
        data that was used to populate the results
        +
        +

        +
        +
        +
        +
        +

        select2-focus

        +

        Fired when the control is focussed +

        +
        +
        +
        +
        +

        select2-blur

        +

        Fired when the control is blurred +

        +
        +
        + + +
        +
        +

        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 + +
        +