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
- Rich UI. Select boxes made by Selectivity have rich functionality, work out of the box and are customizable.
- Modular. Selectivity's modular approach is aimed to make it easy to create custom builds with just the features that you care about and to easily swap modules for custom ones.
- Light-weight. Selectivity.js is smaller than comparable selection libraries, even if you're using a build with all features packed in.
- Compatibility. Selectivity.js can be used without any external libraries, but also offers a jQuery build that is compatible with both jQuery (including custom builds without Sizzle) and Zepto.js, and a build that is compatible with React. It's your choice how you want to use it.
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'
});
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'
});
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'
});
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
});
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'
});
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>'
);
}
}
});
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).
|
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
|
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:
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:
|
showDropdown |
Boolean
|
Set to
false if you don't want to use any dropdown (you can still open it programmatically using
open() ). |
show
|
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
|
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:
|
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:
|
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:
|
"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:
|
"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:
|
"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:
|
More information
For more information, see the GitHub page.