Fork me on GitHub

Select2

Select2 is a jQuery based replacement for select boxes. It supports searching, remote data sets, and infinite scrolling of results. Look and feel of Select2 is based on the excellent Chosen library.

Learn more on GitHub» Download»

Warning!

This page refers to an unreleased version of Select2 which may be unstable. For the latest stable and previous versions please see links at the top. The code for this version is only available in the master branch.

Changelog

  • Support for selection of multiple values. See multiple option in the docs.
  • Ability to reset back to placeholder once a selection has been made. See allowClear option in the docs.
  • Simplified paging of remote datasets by tracking the page number automatically.

Examples


The Basics

Select2 can take a regular select box like this:

and turns it into:


with support for quick option filtering via a search box

Example Code

<head>
    <link href="select2.css" rel="stylesheet"/>
    <script src="select2.js"></script>
    <script>
        $(document).ready(function() { $("#e1").select2(); });
    </script>
</head>
<body>
    <select id="e1">
        <option value="AL">Alabama</option>
        ...
        <option value="WY">Wyoming</option>
    </select>
</body>

Multi-Value Select Boxes

Select2 also supports multi-value select boxes. The select below is declared with the multiple attribute. Select2 automatially picks up on this:


Example Code

          

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

            

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


         

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

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:

Example Code


              

Select2 uses jQuery's $.ajax function to execute the remote call. If you would like to use another transport you can specify your own 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:

Example Code


            

Pragmatic Access

Select2 supports methods that allow pragmatic control of the componentL



Example Code


         

Documentation


Constructor

ParameterTypeDescription
minimumInputLengthintNumber of characters necessary to start a search
placeholderobject/string

Initial value that is selected if no other selection is made.

The value can be specified either as an object or as a string. If specified as a string any custom formatSelection function will be bypassed and the string value will be rendered directly.

The placeholder can also be specified as a data-placeholder attribute on the select or input element that Select2 is attached to. In this case only string values are supported

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.

allowClear boolean

Whether or not a clear button is displayed when the select box has a selection. The button, when clicked, resets the value of the select box back to the placeholder, thus this option is only available when the placeholder is specified.

Also, note that this option only works with non-multi-value based selects because multi-value selects always provide such a button for every selected option.

multiple boolean

Whether or not Select2 allows selection of multiple values.

When Select2 is attached to a select element this value will be ignored and select's multiple attribute will be used instead.

formatSelectionfunction Function used to render the current selection.
formatSelection(object)
ParameterTypeDescription
objectobjectThe selected result object returned from the query function
<returns>stringHtml that represents the selection
The default implementation expects the object to have a text property that is returned.
formatResultfunction Function used to render a result that the user can select.
formatResult(object)
ParameterTypeDescription
objectobjectOne of the result objects returned from the query function
<returns>stringHtml that represents the result
The default implementation expects the object to have a text property that is returned.
formatNoMatchesfunction Function used to render the "No matches" message
formatNoMatches(term)
ParameterTypeDescription
termstringSearch string entered by user
<returns>stringMessage html
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
query function Function used to query results for the search term.
query(options)
ParameterTypeDescription
options.termstringSearch string entered by user
options.pageint1-based page number tracked by Select2 for use with infinite scrolling of 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.
result.morebooleantrueif more results are available for the current search term

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

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
urlstringAjax url
dataTypestringtData 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
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
<returns>objectObject containing url paramters
resultsfunction Function used to build the query results object from the ajax response
results(term, page)
ParameterTypeDescription
termstringSearch term
pageintPage number that was passed into the data function above
<returns>objectResults object. See "options.callback" in the "query" function for format.

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

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

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 select Value of the value attribute of the option that should be selected Array of values specified to the left. null for empty.
Attached to input[type=hidden] An object representing the selection. Should at least contain an id key. The rest of the keys should be determined by the custom rendering function, the default rendering function only needs an additional text key Array of objects specified to the left. null for empty.
Example:
alert("Selected value is: "+$("#e8").select2("val")); $("#e8").select2("val", {id:"CA", text:"Califoria"});

About