View on GitHub

Selectivity.js

Modular and light-weight selection library

Download this project as a tar.gz file

Deprecation notice

At Speakap, we are migrating to a more responsive component library. As such, we will be migrating away from Selectivity, and we will no longer be maintaining this library. If you are interested in taking over ownership, please file an issue. Thanks for all the support!

Benefits

Examples

Select a single city

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

Select multiple cities

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

    
React
jQuery

Select a city by country

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

    
React
jQuery

Select a city by timezone

<Selectivity.React
    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}
/>
    
$('#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
});

    
React
jQuery

Enter one or more email addresses

<Selectivity.React
    inputType='Email'
    placeholder='Type or paste email addresses'
/>
    
$('#example-5').selectivity({
    inputType: 'Email',
    placeholder: 'Type or paste email addresses'
});
    
React
jQuery

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.



            
<Selectivity.React
    ajax={{
        url: 'https://api.github.com/search/repositories',
        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) };
        },
        fetch: function(url, init, queryOptions) {
            return fetch(url)
                .then(function(response) {
                    if (response.ok) {
                        return response.json();
                    } else {
                        throw new Error('Unexpected AJAX response');
                    }
                })
                .then(function(data) {
                    return {
                        results: data.items.map(function(item) {
                            return {
                                id: item.id,
                                text: item.name,
                                description: item.description
                            };
                        }),
                        more: (data.total_count > queryOptions.offset + data.items.length)
                    };
                });
        }
    }}
    placeholder='Search for a repository'
    templates={{
        resultItem: function(item) {
            return (
                <div className='selectivity-result-item' data-item-id={item.id}>
                    <b>{item.text}</b><br />
                    {item.description}
                </div>
            );
        }
    }}
/>
    
$('#example-6').selectivity({
    ajax: {
        url: 'https://api.github.com/search/repositories',
        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) };
        },
        fetch: function(url, init, queryOptions) {
            return $.ajax(url).then(function(data) {
                return {
                    results: $.map(data.items, function(item) {
                        return {
                            id: item.id,
                            text: item.name,
                            description: item.description
                        };
                    }),
                    more: (data.total_count > queryOptions.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>'
            );
        }
    }
});
    
React
jQuery

Setup

For setup instructions, please see the GitHub project page.

API

Older references: v2

jQuery

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.

React

Render a Selectivity component as follows:

<Selectivity.React {...options} />

This will create a <div> element in which the Selectivity control itself is rendered. Note that besides the options documented below, also some generic attributes for divs are allowed on this element ( className, onClick, onInput, style, ...).

Options

The following options are supported:

Option Type Description
ajax Object This object is used for convenience for loading result items through AJAX requests from 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 fetch method (see below).
fetch
The function to use for fetching the AJAX results. By default, window.fetch() is used, unless you use a jQuery build. If you use a jQuery build, it will automatically replace the default with a wrapper that uses $.ajax() internally. If you don't use a jQuery build, you are encouraged to ship a polyfill for window.fetch(), because not all browsers support this yet (or you can always specify this property to implement custom fetch logic).

If you implement this callback yourself, make sure you can accept the same parameters as window.fetch(). In addition, you will receive a third parameter which matches the parameter to the query() function documented below.

Make sure you return a Promise that resolves to either a Response object, an Array with result items, or an object with a results array and an optional more boolean. The latter case is further documented on the query() function below.
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 two parameters: term and error. The first is the term being searched for while the latter is the error object that resulted from the failed request. 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.
quietMillis
Number of milliseconds to wait before submitting AJAX requests when the user is entering a search term. It is advised to use some number around 200 to 300 (milliseconds) to not delay results too much, while not submitting too many requests while the user is typing.
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, just 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.
backspace Highlights BeforeDelete 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 false.
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.

If you're using the React API, you must also specify the onChange listener to get updates when the data changes, or use defaultData instead.
defaultData *(React only)* 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 defaultValue.

Unlike data, any changes to this property are not reflected on the data of the Selectivity instance.
defaultValue *(React only)* 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 defaultData.

Unlike value, any changes to this property are not reflected on the value of the Selectivity instance.
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.Inputs map or just specify one here as a function. The default value is 'Single', unless multiple is true in which case it is 'Multiple'.

Note: This option cannot be switched after the instance is created.
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.

Note: This option cannot be switched after the instance is created.
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:
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.
shouldOpenSubmenu Function Callback to invoke whenever a result item is highlighted that will decide whether a submenu should be opened. Receives two parameters:
item
The currently highlighted result item.
reason
The reason why the item is being highlighted. Possible values: 'current_value' (the item is being highlighted because it is the current value of the input), 'first_result' (highlighted because it is the first result in the dropdown), 'hovered' (the user hovered over the item).
This function is only called for items for which a submenu is defined.
showDropdown Boolean Set to false if you don't want to use any dropdown (you can still open it programmatically using open()).
show SearchInput InDropdown 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.
suppress WheelSelector String or null The Selectivity Dropdown by default suppresses wheel 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 src/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.
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.

If you're using the React API, you must also specify the onChange listener to get updates when the data changes, or use defaultValue instead.

Methods

If you're using the jQuery API, 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' })

If you're using the React API, the methods to use are somewhat limited, because you are expected to use the component declaratively as much as possible. But for those methods available, you can call them like ordinary methods if you have a reference to the component instance:

this.refs.selectivity.getData()

add

(jQuery only, 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

(jQuery only)

Clears the selection.

Example:

$(selector).selectivity('clear')

close

Closes the dropdown.

data

(React: Only getData() is provided)

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 with jQuery:
$(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' }])
// returns the current data with React:
this.refs.selectivity.getData()

destroy

(jQuery only)

Destroys the Selectivity instance.

Note: If you had initialized your Selectivity instance from a <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

(jQuery only, 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

(jQuery only)

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

(jQuery only)

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

(React: Only getValue() is provided)

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 with jQuery:
$(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])
// returns the current value with React:
this.refs.selectivity.getValue()

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"
(React: onChange)
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.
data
The new data of the input. Might be null, an object with id and text properties, or an array of such objects.
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. Might be null, an ID or an array of IDs.
"selectivity-close"
(React: onDropdownClose)
Emitted when the dropdown is closed.
"selectivity-highlight"
(React: onHighlight)
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"
(React: onDropdownOpen)
Emitted when the dropdown is opened.
"selectivity-opening"
(React: onDropdownOpening)
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"
(React: onSelect)
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"
(React: onSelecting)
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.