View on GitHub

Selectivity.js

Modular and light-weight selection library for jQuery and Zepto.js

Download this project as a tar.gz file

Benefits

Examples

Select a single city

$('#example-1').selectivity({
    allowClear: true,
    items: ['Amsterdam', 'Antwerp'/*, ...*/],
    placeholder: 'No city selected'
});

Select multiple cities

$('#example-2').selectivity({
    items: ['Amsterdam', 'Antwerp'/*, ...*/],
    multiple: true,
    placeholder: 'Type to search a city'
});

Select a city by country

$('#example-3').selectivity({
    allowClear: true,
    items: [{
        text: 'Austria',
        children: [ { id: 54, text: 'Vienna' } ]
    } /*, ...*/],
    placeholder: 'No city selected'
});

Select a city by timezone

$('#example-4').selectivity({
    allowClear: true,
    items: [{
        id: '+00:00',
        text: 'Western European Time Zone',
        submenu: {
            items: [
                { id: 4, text: 'Barcelona' }
                /*, ...*/
            ],
            showSearchInput: true
        }
    } /*, ...*/],
    placeholder: 'No city selected',
    showSearchInputInDropdown: false
});

Enter one or more email addresses

$('#example-5').selectivity({
    inputType: 'Email',
    placeholder: 'Type or paste email addresses'
});

Search a GitHub repository

Note: If this example stops working, please wait a few minutes. There is an active rate-limit in the GitHub API.

$('#example-6').selectivity({
    ajax: {
        url: 'https://api.github.com/search/repositories',
        dataType: 'json',
        minimumInputLength: 3,
        quietMillis: 250,
        params: function(term, offset) {
            // GitHub uses 1-based pages with 30 results, by default
            return { q: term, page: 1 + Math.floor(offset / 30) };
        },
        processItem: function(item) {
            return {
                id: item.id,
                text: item.name,
                description: item.description
            };
        },
        results: function(data, offset) {
            return {
                results: data.items,
                more: (data.total_count > offset + data.items.length)
            };
        }
    },
    placeholder: 'Search for a repository',
    templates: {
        resultItem: function(item) {
            return (
                '<div class="selectivity-result-item" data-item-id="' + item.id + '">' +
                    '<b>' + escape(item.text) + '</b><br>' +
                    escape(item.description) +
                '</div>'
            );
        }
    }
});

API v2

Call $(selector).selectivity(options) to initialize a Selectivity instance on the element specified by the given selector. The element should be a <div> element which will be used as container to render the Selectivity control in. If the element is a <select> element instead, this element will be used for initializing some of the options below after which it is replaced with a <div> element to contain the Selectivity control.

The following options are supported:

Option Type Description
ajax Object This object is used for convenience for loading result items through AJAX requests to a remote resource. Below is an overview of properties that may be set on this object. Any other properties on this object are passed directly to the transport, which by default is $.ajax(). t
Property Description
formatError Function that returns an HTML-formatted error message in case of an AJAX error. By default, Selectivity.Locale.ajaxError is used. The function receives four paramenters: term, jqXHR, textStatus and errorThrown. The first is the term being searched for, while the other three are the parameters passed to the error callback of $.ajax. Please be aware that because the function returns raw HTML, you are responsible for properly escaping any output to prevent XSS attacks.
minimumInputLength An integer that specifies the minimum amount of characters required before an actual AJAX query will be performed.
params Function that should return an object with additional query parameters to be added to the URL. Receives term and offset parameters. The term is a search term to search for and the offset is an integer of results that should be skipped for pagination.
processItem Function that processes an individual result item. Make sure that the returned item has id and text properties. By default, this is the identity function (a function that simply returns its only parameter).
quietMillis Number of milliseconds to wait before submitting AJAX requests when the user is entering a search term. I would advise to use some number from 200 to 300 (milliseconds) to not delay results too much, while not submitting too many requests while the user is typing.
results Function that interprets the data from the AJAX response and turns it into an object with results and more properties, just like the callback for the top-level query function. The function receives a data parameter containing the parsed AJAX response and an offset parameter used for pagination.
transport The transport to use for submitting the AJAX requests. By default, $.ajax is used, but you can specify any other function to use instead, as long as it's API-compatible with $.ajax.
url URL to send the AJAX requests to. This can be given either as a string or as a function returning a string. If a function is given, it is passed an options object with offset and term properties, like the query method documented below. Note the URL does not need to contain (all) query parameters, as those can be specified using the params option.
allowClear Boolean Set to true to allow the selection to be cleared. This option only applies to single-value inputs.

If you have used a <select> element to initialize the Selectivity instance, this option defaults to true unless the element has a required attribute.
allowDuplicates Boolean If true, enables the addition of duplicate items to the input.
backspaceHighlightsBeforeDelete Boolean If set to true, when the user enters a backspace while there is no text in the search field but there are selected items, the last selected item will be highlighted and when a second backspace is entered the item is deleted. If false, the item gets deleted on the first backspace. The default value is true on devices that have touch input and false on devices that don't.
closeOnSelect Boolean Set to false to keep the dropdown open after the user has selected an item. This is useful if you want to allow the user to quickly select multiple items. The default value is true.
createTokenItem Function Function to create a new item from a user's search term. This is used to turn the term into an item when dropdowns are disabled and the user presses Enter. It is also used by the default tokenizer to create items for individual tokens. The function receives a token parameter which is the search term (or part of a search term) to create an item for and must return an item object with id and text properties or null if no token can be created from the term. The default is a function that returns an item where the ID and text both match the term for any non-empty string and which returns null otherwise.

This option only applies to multiple-value inputs.
data Object or Array Initial selection data to set. This should be an object with id and text properties in the case of input type 'Single', or an array of such objects otherwise. This option is mutually exclusive with value.
dropdown Function Custom dropdown implementation to use for this instance.
dropdownCssClass String Optional CSS class to add to the dropdown's top-level element.
initSelection Function Function to map values by ID to selection data. This function receives two arguments, value and callback. The value is the current value of the selection, which is an ID or an array of IDs, depending on the input type. The callback should be invoked with an object containing id and text properties, or an array of such objects (again, depending on the input type).
inputType String or Function The input type to use. Default input types include 'Multiple', 'Single' and 'Email', but you can add custom input types to the Selectivity.InputTypes map or just specify one here as a function. The default value is 'Single', unless multiple is true in which case it is 'Multiple'.
items Array Array of items from which to select. Should be an array of objects with id and text properties. As convenience, you may also pass an array of strings, in which case the same string is used for both the ID and the text. Items may be nested by adding a children property to any item, whose value should be another array of items. Items that have children may omit having an ID.

If items are specified, all items are expected to be available locally and all selection operations operate on this local array only. If omitted, items are not available locally, and the query option should be provided to fetch data.

If you have used a <select> element to initialize the Selectivity instance, its <option> and <optgroup> elements are used to initialize the items array.
matcher Function Function to determine whether text matches a given search term. Note this function is only used if you have specified an array of items. Receives two arguments: term and text. The term is the search term, which for performance reasons has always been already processed using Selectivity.transformText(). The text is the text that should match the search term.

The function should return true if the text matches the term, and false otherwise.
multiple boolean May be set to true as short-hand for specifying inputType: 'Multiple'.

If you have used a <select> element to initialize the Selectivity instance, this option is set to true when the element has a multiple attribute.
placeholder String Placeholder text to display when the element has no focus and selected items.

If you have used a <select> element to initialize the Selectivity instance, this option may be set through the data-placeholder attribute.
positionDropdown Function Function to position the dropdown. Receives $dropdownEl (the element to be positioned) and $selectEl (the element of the Selectivity instance) as arguments. The default implementation positions the dropdown element under the Selectivity instance's element and gives it the same width as well.
query Function Function to use for querying items. Receives a single object with the following properties:
Property Description
callback This is the function that should be invoked when the results are available. It should be passed a single object with results and more properties. The first is an array with result items in the same format as the items option and the latter is an optional boolean that may be set to true to indicate more results are available through pagination.
error Another function that may be called to indicate the query operation failed. You should pass it a message which will be displayed to the user. Optionally you can pass an options object as the second argument, which may have an escape property which, if set to false, indicates the message contains raw HTML and should not be escaped. Be aware this does make you responsible for properly escaping user input to avoid XSS attacks.
offset An integer that indicates how many results should be skipped when returning more results. This is used to implement pagination.
term The search term the user is searching for. Unlike with the matcher function, the term has not been processed using Selectivity.transformText().
This option is ignored if the items option is used.
readOnly Boolean If true, disables any modification of the input.
removeOnly Boolean If true, disables any modification of the input except removing of selected items.
showDropdown Boolean Set to false if you don't want to use any dropdown (you can still open it programmatically using open()).
showSearchInputInDropdown Boolean Set to false to remove the search input used in dropdowns. This option only applies to single-value inputs, as multiple-value inputs don't have the search input in the dropdown to begin with. The default is true.
suppressMouseWheelSelector String or null The Selectivity Dropdown by default suppresses mousewheel events so that any scrolling in the dropdown doesn't affect the scroll position of the page. Through this option you can select which selector should be monited for scroll events to suppress. Set it to null to disable suppressing of mousewheel events altogether. The default value is ".selectivity-results-container".
templates Object Object with instance-specific templates to override the global templates assigned to selectivity.Templates. Inline documentation for the templates is provided in selectivity-templates.js.
tokenizer Function Function for tokenizing search terms. Will receive the input (the input string to tokenize), selection (the current selection data), createToken (callback to create a token from the search terms, should be passed an item object with id and text properties) and options (the options set on the Selectivity instance) arguments. Any string returned by the tokenizer function is treated as the remainder of untokenized input. This option only applies to multiple-value inputs.
tokenSeparators Array Array of string separators which are used to separate the search term into tokens. If specified and the tokenizer property is not set, the tokenizer property will be set to a function which splits the search term into tokens separated by any of the given separators. The tokens will be converted into selectable items using the createTokenItem function. The default tokenizer also filters out already selected items. This option only applies to multiple-value inputs.
trimSpaces Boolean If true, removes whitespace from both sides of the input items.
value ID or Array Initial value to set. This should be an ID (string or number) in the case of input type 'Single', or array of IDs otherwise. This property is mutually exclusive with data.

Methods

Methods are invoked by passing the name of the method, followed by any arguments, to the selectivity() function. Example:

$(selector).selectivity('data', { id: 1, text: 'Amsterdam' })

add

(multiple-value inputs only)

Adds an item to the selection.

Argument Type Description
item ID or Object The item to add, either as ID or object with id and text properties.

Examples:

$(selector).selectivity('add', 1)

$(selector).selectivity('add', { id: 1, text: 'Amsterdam' })

clear

Clears the selection.

Example:

$(selector).selectivity('clear')

close

Closes the dropdown.

data

Sets or gets the data of the selection. If no argument is given, the current data is returned. Otherwise, the data is set to the argument given.

When new data is set, the appropriate change event is automatically generated, unless triggerChange is set to false.

Argument Type Description
data Object or Array The new data to set, either as object with id and text properties (for single-value inputs) or as array of such objects (for multiple-value inputs).
options Object Optional options object. May contain the following property:
triggerChange
Set to false to suppress the change event. Note this will also cause the UI to not update automatically; so you may want to call rerenderSelection() manually when using this option.

Examples:

// returns the current data:
$(selector).selectivity('data')
// sets new data on a single-value input:
$(selector).selectivity('data', { id: 1, text: 'Amsterdam' })
// sets new data on a multiple-value input:
$(selector).selectivity('data', [{ id: 1, text: 'Amsterdam' }, { id: 2, text: 'Antwerp' }])

destroy

Destroys the Selectivity instance.

Note: If you had initialized your Selectivity instance from an <input> or <select> element, that element is gone forever and you won't get it back by destroying the Selectivity instance.

focus

Focuses the search input.

open

Opens the dropdown.

remove

(multiple-value inputs only)

Removes an item from the selection.

Argument Type Description
item ID or Object The item to remove, either as ID or object with id and text properties.

Examples:

$(selector).selectivity('remove', 1)

$(selector).selectivity('remove', { id: 1, text: 'Amsterdam' })

rerenderSelection

Re-renders the selection.

Normally the UI is automatically updated whenever the selection changes, but you may want to call call this method explicitly if you've updated the selection with the triggerChange option set to false.

setOptions

Sets one or more options of the Selectivity instance.

Argument Type Description
options Object Object with one or more options. All options that can be passed to the constructor are valid, with the exception of data and value.

Example:

$(selector).selectivity('setOptions', { readOnly: true })

value / val

Sets or gets the value of the selection. If no argument is given, the current value is returned. Otherwise, the value is set to the argument given.

Note: When setting the value of the selection, the full data (including the text properties) is updated as well. In order to detect the right text for the ID(s), Selectivity will inspect the items array to look up the corresponding item(s). If no items have been provided, it is assumed the text should be equal to the ID. If this is not what you want, you may want to pass the initSelection option to the Selectivity instance to override this process.

When a new value is set, the appropriate change event is automatically generated, unless triggerChange is set to false.

Argument Type Description
value ID or Array The new value to set, either as single ID (for single-value inputs) or an array of IDs (for multiple-value inputs).
options Object Optional options object. May contain the following property:
triggerChange
Set to false to suppress the change event. Note this will also cause the UI to not update automatically; so you may want to call rerenderSelection() manually when using this option.

Examples:

// returns the current value:
$(selector).selectivity('value')
$(selector).selectivity('val')
// sets a new value on a single-value input:
$(selector).selectivity('value', 1)
// sets a new value on a multiple-value input:
$(selector).selectivity('value', [1, 2])

Events

All of these events are emitted on the element to which the Selectivity instance is attached and can be listened to using jQuery's on() method.

Note: If you have used a <select> element for initializing the Selectivity instance, you should realize it is replaced by a <div> element after the initialization. Any events will be triggered on the latter.

Event Description
"change" Emitted when the selection has been changed. The event object will contain the following properties:
added
If an item has been added to the selection of a multiple-value input, this property contains that item.
removed
If an item has been removed from the selection of a multiple-value input, this property contains that item.
value
The new value of the input. Either an ID or an array of IDs.
"selectivity-close" Emitted when the dropdown is closed.
"selectivity-highlight" Emitted when an item in the dropdown is highlighted. The event object will contain the following properties:
id
The ID of the item being highlighted.
item
The item being highlighted.
"selectivity-open" Emitted when the dropdown is opened.
"selectivity-opening" Emitted when the dropdown is about to be opened. You can call preventDefault() on the event object to cancel the opening of the dropdown.
"selectivity-selected" Emitted when an item has been selected. The event object will contain the following properties:
id
The ID of the item being selected.
item
The item being selected.
"selectivity-selecting" Emitted when an item is about to be selected. You can call preventDefault() on on the event object to prevent the item from being selected. The event object will contain the following properties:
id
The ID of the item being selected.
item
The item being selected.

More information

For more information, see the GitHub page.