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

Benefits

  • Rich UI. Select boxes made by Select3 have rich functionality, work out of the box and are customizable.
  • Modular. Select3’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. Select3 is smaller than comparable selection libraries, even if you’re using the “full” build with all features packed in.
  • Compatibility. Select3 can be used with both jQuery and Zepto.js and is compatible with jQuery builds without Sizzle.

 

It is difficult to customize the styling, and introducing subtle tweaks to its behavior typically meant maintaining a private fork. More specifically, I wanted to make the following changes:

  • Use custom templates, instead of the ones that are hard-coded in Select2. This would also open up the possibility of not loading the image sprite included with Select2, but instead use FontAwesome icons that I already use in my projects.
  • Use custom loading indicators, instead of the spinner GIF included by Select2.
  • I wanted to make it easier to support a use case where Select2 is used without any selection dropdown, but with the proper tokenization.
  • Make Select2 work with jQuery builds without Sizzle for better performance. Patches for this have been accepted in Select2, but unfortunately it’s a moving target causing repeated breakage. Also, once Sizzle is no longer required, it becomes much easier to support Zepto.js.
  • Personally, I preferred a more modern codebase to work with, rather than the huge monolithic library that is Select2. This also includes proper documentation of the code as well as good test coverage. At this point also support for any IE version older than 10 can be dropped.

Having said that, if you’re a user of Select2 and don’t recognize yourself in any of these issues, I advise you to keep using Select2. It’s feature-rich and actively supported, so don’t fix what ain’t broken 😉

Browser Support

  • Chrome
  • Firefox
  • Internet Explorer 10+
  • Safari 6+

Note that while Internet Explorer versions older than 10 are not supported, you might be able to get them to work, possibly with the use of some polyfills. Reports of success or patches to create a “legacy” build would be welcomed.

Dependencies

Select3 only relies on jQuery or Zepto.js being loaded on the page to work.

In addition, the default templates assume that you have included FontAwesome in your page to display the icons.

API

Call $(selector).select3(options) to initialize a Select3 instance on the element specified by the given selector. The following options are supported:

OptionTypeDescription
allowClearBooleanSet to true to allow the selection to be cleared. This option only applies to single-value inputs.
backspaceHighlightsBeforeDeleteBooleanIf 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.
closeOnSelectBooleanSet 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.
createTokenItemFunctionFunction 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.
dataObject or ArrayInitial 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.
dropdownFunctionCustom dropdown implementation to use for this instance
dropdownCssClassStringOptional CSS class to add to the top-level dropdown element.
initSelectionFunctionFunction 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 or array of objects, respectively, containing id and text properties.
inputTypeString or FunctionThe input type to use. Default input types include ‘Multiple’, ‘Single’ and ‘Email’, but you can add custom input types to the Select3.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’.
itemsArrayArray 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. If items are given, all items are expected to be available locally and all selection operations operate on this local array only. If null, items are not available locally, and the query option should be provided to fetch remote data.
matcherFunctionFunction 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: item and term. The item is the item that should match the search term. The term is the search term, which for performance reasons has always been already processed using Select3.transformText(). The method should return the item if it matches, and null otherwise. If the item has a children array, the matcher is expected to filter those itself (be sure to only return the filtered array of children in the returned item and not to modify the children of the item argument).
placeholderStringPlaceholder text to display when the element has no focus and selected items.
positionDropdownFunctionFunction to position the dropdown. Receives $dropdownEl (the element to be positioned) and $selectEl (the element of the Select3 instance) as arguments. The default implementation positions the dropdown element under the Select3’s element and gives it the same width as well.
queryFunctionFunction to use for querying items. Receives a single object as argument with the callback, offset and term properties. The callback 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 and the latter is an optional boolean that may be set to true indicate more results are available through pagination. Offset is a property is only used for pagination and indicates how many results should be skipped when returning more results. The term is the search term the user is searching for. Unlike with the matcher function, the term has not been processed using Select3.transformText(). This option is ignored if the items option is used.
searchInputPlaceholderStringPlaceholder text to display in the search input in the dropdown.
showDropdownBooleanSet to false if you don’t want to use any dropdown (you can still open still open it programmatically using open()).
showSearchInputInDropdownBooleanSet 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.
suppressMouseWheelSelectorString or nullThe Select3 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 ".select3-results-container".
templatesObjectObject with instance-specific templates to override the global templates assigned to Select3.Templates.
tokenizerFunctionFunction 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 Select3 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.
tokenSeparatorsArrayArray 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.
valueID or ArrayInitial 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.

For documentation about all the available methods once Select3 has been instantiated, I refer to the inline documentation in the source files for now.

Events

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

EventDescription
"change"Emitted when the selection has been changed. Additional properties on the event object: added, removed and value.
"select3-closed"Emitted when the dropdown is closed.
"select3-highlight"Emitted when an item in the dropdown is highlighted. Additional properties on the event object: item and value.
"select3-open"Emitted when the dropdown is opened.
"select3-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.
"select3-selected"Emitted when an item has been selected. Additional properties on the event object: id and item.
"select3-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. Additional properties on the event object: id and item.

Migrating from Select2

Before you decide to migrate from Select2 to Select3, you should consider that not every feature supported by Select2 is supported by Select3. So check beforehand whether Select3 actually meets your requirements.

Unsupported features

The following is an (incomplete) list of features which Select3 currently lacks:

  • Reordering of selected items. Select2 allows reordering of selected items, for example through drag ‘n drop. Select3 doesn’t and there are curently no plans to implement this.
  • AJAX. Select2 has a built-in AJAX query function that makes it easier to perform AJAX requests for fetching requests. This is a convenience feature as you can achieve the same result by calling $.ajax() in the query function, but it is one Select3 currently lacks.
  • Formatting functions. Select2 allows you to specify a wide range of format*() functions in the options. With Select3, it is hoped you won’t have much need for these as Select3 allows for much easier customization of templates. However, practice will have to show if some of these are still desired.
  • Options. Select3 lacks some miscellaneous options supported by Select2. Notable omissions are selectOnBlur, maximumSelectionSize, and minimumInputLength among others.
  • Events. Select2 currently emits more events than Select3 does. Notable omissions are ‘select2-clearing’, ‘select2-focus’ and ‘select2-blur’ among others.

Notable differences

  • With Select2, you can take a <select> or <input> element in the DOM and initialize your Select2 instance based on that. Instead, to position a Select3 instance in the DOM you attach it to an empty <div> element and all options you want pass to Select3 are specified through the constructor method. An additional module is planned for Select3 that will simulate the Select2 approach, but this is not a high priority right now.
  • Select2 has explicit support for tags through the tags option. With Select3, tagging is also supported, but works through the regular items option.

Miscellaneous

  • If you have customized the CSS you use with Select2, you will have to take into account that you may need to customize it again for Select3 as the templates are very different.
  • Some properties are named differently, even though they have very similar meaning. Examples:
    • createSearchChoice is now createTokenItem.
    • The choice parameter to events is now called item.

SOURCE: https://arendjr.github.io/select3/

DEMO: https://arendjr.github.io/select3/