Types
Dropdown
A dropdown
Selection
A dropdown can be used to select between choices in a form
Search Selection
A selection dropdown can allow a user to search through a large list of choices.
Unfilterable items in Search Selection
You can define items to always be listed, even if the search filter would not match, by adding the unfilterable
class to the desired items
Search ignoring Diacritics
A selection dropdown can allow a user to ignore all Diacritics while searching.
Clearable Selection
A clearable selection dropdown can allow a user to cancel to cancel a previous selection
Multiple Selection
A selection dropdown can allow multiple selections
Multiple Search Selection
A selection dropdown can allow multiple search selections
A multiple search selection dropdown can keep its search value on item selection so the menu stays filtered
Search Dropdown
A dropdown can be searchable
Search In-Menu
A dropdown can include a search prompt inside its menu
Inline
A dropdown can be formatted to appear inline in other content
Show me posts by
Trending repos
today
Pointing
A dropdown can be formatted so that its menu is pointing
Simple
A simple dropdown can open without Javascript
Content
Header
A dropdown menu can contain a header
Divider
A dropdown menu can contain dividers to separate related content
Icon
A dropdown menu can contain an icon.
Description
A dropdown menu can contain a description.
The description can be shown vertically underneath the entry using vertical item
.
Label
A dropdown menu can contain a label.
Message
A dropdown menu can contain a message.
Floated Content
A dropdown menu can contain floated content.
Input
A dropdown menu can contain an input
Image
A dropdown menu can contain an image
Actionable
A dropdown menu can contain an actionable item which performs a custom callback once clicked instead of being selected itself
States
Loading
A dropdown can show that it is currently loading data
Error
An errored dropdown can alert a user to a problem
Active
An active dropdown has its menu open
Disabled
A disabled dropdown menu or item does not allow user interaction
Read-Only
A dropdown can be read-only and does not allow user interaction
Variations
Size
A dropdown can have different sizes
Scrolling
A dropdown can have its menu scroll
Inverted
A dropdown can be inverted
The menu of a non-inverted dropdown can be inverted
Compact
A compact dropdown has no minimum width
Fluid
A dropdown can take the full width of its parent
Height
A selection dropdown can be long (2x of default height) so that more items can be glanced.
Very long: 3x of default height.
Menu Direction
A dropdown menu or sub-menu can specify the direction it should open
Columnar Menu
A selection dropdown can allow menu to be equally divided so that more items can be glanced.
Three columns.
Four columns.
Five columns.
Selection Dropdowns
Clearable
Using the clearable setting will let users remove their selection from a dropdown.
Maximum Selections
Using maxSelections
lets you force a maximum number of selections. You can also use form validation rules to specify minimum and maximum validation settings for multi-selects inside forms.
Tagging and User Additions
Using allowAdditions: true
gives users the ability to add their own options. This can work with either single or multiple search select dropdowns
Stuck User Additions
While using allowAdditions: true
together with hideAdditions: false
, the first line indicating "add:" with the user addition may not be correctly displayed, depending on the container size and the distance between topmost visible item and menu's top item.
You can stick this addition line to the top of the menu by providing the additional stuck
class.
Text Labels
Sometimes multiselect include options which are long and would appear awkwardly as labels. Setting useLabels: false
will display a selected count, and allow reselection directly from the menu.
Clearing Dropdown
You can reset a form field to its placeholder value
Restoring Defaults
You can restore a dropdown to its value set on page load using the restore defaults
behavior. If no default text is set on load, restore defaults will restore placeholder text
Upward
A dropdown menu will automatically change which direction it opens if it can't fit on screen. If you need a dropdown to open in a specific direction you can specify it when initializing a dropdown.
Remote Content
Match Search Query on Server
Search selection dropdowns can specify API settings for retrieving values remotely, this can use either a named API action
or url
.
Using API can allow users to select choices from large datasets that would be too large to include directly in page markups.
If your backend is not designed to return the correct markup you can use API's onResponse
callback to adjust the format of an API response after it is received from the server.
Requests for the same API endpoints will automatically cached locally, to avoid server roundtrips. You can disable this by adjusting the cache
API setting.
Return All Choices Remotely
When possible choicesets are large, ideally API results should only return values matching the passed query term to reduce transmissions over the wire. However if there are only a few hundred or less choices, you may consider returning the full set of results from an API endpoint and filtering them against the query clientside using the setting filterRemoteData: true
.
Menus
Changing Transitions
A dropdown can specify a different transition.
Multiple Levels
A dropdown menu can also contain sub menus inside of it
My favorite animal breed isCategory Selection
Using a multi-level menu with allowCategorySelection: true
will allow items with sub-menus to be selected.
Preserving User Selections
This example uses a preset text value to preserve the menu item on page navigation
Current action:Dropdown Dividers / Headers
A dropdown menu can contain dividers and/or headers to separate related content. Using hideDividers
lets you control how the elements are handled while filtering items.
Adjusting Actions
Link Dropdowns
Dropdowns support different default actions that can occur when an item is selected. For example, you can set your dropdown not to change its text, or select a value from its menu.
Coupling
Button Group
A button group can be formatted to show additional content as a dropdown
Menu
A menu element can contain a dropdown
Initializing
Initializing Existing HTML
Initializing a dropdown with pre-existing HTML allows for greater performance than initializing a dropdown directly on a select
element.
Initializing with Javascript Only
You can specify a list of values in the settings object to avoid having to stub the html yourself.
Adding selected: true
to an item will have that item selected by default.
You can also use the placeholder
setting to specify placeholder text before an option is selected.
You can also add headers by adding type: 'header'
to values
.
You can also add submenus by adding type: 'menu'
or type: 'left menu'
and another values
object to the item itself. New in 2.8.8
Display images and/or icons by value setting
Images and/or icons in front of an item can be dynamically created by providing image paths, icon names or classnames for different styling
To avoid adding the classNames to every item entry (for example if you want to display a list of avatars or flags), you could override the default setting for className.image
or className.icon
when initializing the dropdown
Display a (vertical) description by value setting
An additional item description (optionally displayed vertically) can be dynamically created by providing two extra attributes
Supporting image labels for multiselection
If needed, you can adjust the classname for multiselection labels to make use of image label
Specifying Different Text & Hidden Input Values
You can specify different values for selected text, and selected form values by adding data-text
or data-value
to any item. This is useful if you include additional data, like icons, that you want to appear only inside the dropdown menu.
Converting Form Elements
For convenience, select
elements can automatically be converted to selection dropdown
. A select options with blank string values will be converted to prompt text.
When creating the dropdown from a select, an existing data-text attribute is preserved, so the displayed text can be different than the in-dropdown text.
Hybrid Form Initialization
As a third option, you can include a wrapper around your select
so that it will appear correctly on page load, but will then populate the hidden menu when Javascript fires. In this case, the select
element does not receive the ui dropdown
class.
Searching Dropdowns
Using a search selection dropdown
will allow you users to search more easily through large lists. This can also be converted directly from a form select element.
Multiple Selections
You can allow multiple selections by the multiple
property on a select
element, or by including the class multiple
on a dropdown.
When pre-existing HTML with a hidden input is used, values will be passed through a single value separated by a delimiter. The default is "," but this can be changed by adjusting the delimiter
setting.
Dropdown
Select
Specifying Select Action
Dropdowns have multiple built-in actions that can occur on item selection. You can specify a built-in action by passing its name to settings.action
or pass a custom function that performs an action.
Action | Description |
---|---|
activate (Default) | Selects current item, adjusts dropdown value and changes dropdown text |
combo | Same as activate, but updates previous elements text instead of self |
select | Selects current item from menu and stores value, but does not change dropdown text |
hide | Hides the dropdown menu and stores value, but does not change text |
function(text, value, element){} | Custom action |
nothing | Does nothing |
To specify a different built in action, simply specify the name.
To trigger only your custom action and no default action, specify your own function for settings.action
.
If you want to have both a built in action occur, and your own custom action use onChange
in combination with action
Behavior
All the following behaviors can be called using the syntax:
Behavior (arguments) | Description |
---|---|
setup menu(values) | Recreates dropdown menu from passed values. values should be an object with the following structure: { values: [ {value, text, name} ] } . |
change values (values) | Changes dropdown to use new values. values structure: [ {value, text, name} ] . |
refresh | Refreshes all cached selectors and data |
toggle | Toggles current visibility of dropdown |
show(callback,preventFocus) | Shows dropdown. If a function is provided to callback , it's called after the dropdown-menu is shown. Set preventFocus to true if you don't want the dropdown field to focus after the menu is shown |
hide(callback,preventBlur) | Hides dropdown. If a function is provided to callback , it's called after the dropdown-menu is hidden. Set preventBlur to true if you don't want the dropdown field to blur after the menu is hidden |
clear (preventChangeTrigger) | Clears dropdown of selection. Set preventChangeTrigger to true to omit the change event (default: false ). |
clear cache | Clears the remote api cache once |
hide others | Hides all other dropdowns that is not current dropdown |
restore defaults (preventChangeTrigger) | Restores dropdown text and value to its value on page load. Set preventChangeTrigger to true to omit the change event (default: false ). |
restore default text | Restores dropdown text to its value on page load |
restore placeholder text | Restores dropdown text to its prompt, placeholder text |
restore default value | Restores dropdown value to its value on page load |
save defaults | Saves current text and value as new defaults (for use with restore) |
set selected(value,preventChangeTrigger) | Sets value as selected. Set preventChangeTrigger to true to omit the change event (default: false ). |
remove selected(value) | Remove value from selected |
set selected([value1, value2]) | Adds a group of values as selected |
set exactly([value1, value2]) | Sets selected values to exactly specified values, removing current selection |
set text(text) | Sets dropdown text to a value |
set value (value,preventChangeTrigger) | Sets dropdown input to value (does not update display state). Set preventChangeTrigger to true to omit the change event (default: false ). |
get text | Returns current dropdown text |
get value | Returns current dropdown input value. When the dropdown was created out of a select tag, the value will always be an array, otherwise a string (delimited when multiple) |
get values | Returns current dropdown input values as array. Useful for multiple selection dropdowns regardless if made out of a div or select |
get item(value) | Returns DOM element that matches a given input value |
get query | Returns current search term entered |
bind touch events | Adds touch events to element |
bind mouse events | Adds mouse events to element |
bind intent | Binds a click to document to determine if you click away from a dropdown |
unbind intent | Unbinds document intent click |
determine eventInModule | Returns whether event occurred inside dropdown |
determine select action(text, value) | Triggers preset item selection action based on settings passing text/value |
set active | Sets dropdown to active state |
set visible | Sets dropdown to visible state |
remove active | Removes dropdown active state |
remove visible | Removes dropdown visible state |
is selection | Returns whether dropdown is a selection dropdown |
is animated | Returns whether dropdown is animated |
is visible | Returns whether dropdown is visible |
is hidden | Returns whether dropdown is hidden |
get default text | Returns dropdown value as set on page load |
get placeholder text | Returns placeholder text |
destroy | Destroys instance and removes all events |
Dropdown
Frequently Used Settings
Setting | Default | Description |
---|---|---|
values | false | When specified allows you to initialize dropdown with specific values. See usage guide for details. |
on | click | Event used to trigger dropdown (Hover, Click, Custom Event) |
clearable | false | Whether the dropdown value can be cleared by the user after being selected. |
ignoreCase | false | Whether values with non matching cases should be treated as identical when adding them to a dropdown. |
ignoreSearchCase | true | Whether values with non matching cases should be treated as identical when filtering the items. |
allowReselection | false | When set to true will fire onChange even when the value a user select matches the currently selected value. |
allowAdditions | false | Whether search selection should allow users to add their own selections, works for single or multiselect. |
hideAdditions | true | If disabled user additions will appear in the dropdown's menu using a specially formatted selection item formatted by templates.addition . |
action | auto |
Sets a default action to occur. (See usage guide) activate (default)
Updates dropdown text with selected value, sets element state to active, updates any hidden fields if available
select
activates menu and updates input fields, but does not change current text
combo
changes text of previous sibling element
nothing
no action occurs
hide
Dropdown menu is hidden
function(text, value, element){}
custom function is executed with values specified in callback
|
minCharacters | 0 | The minimum characters for a search to begin showing results |
match | both | When using search selection specifies how to match values.
both
Matches against text and value
value
matches against value only
text
matches against text only
|
selectOnKeydown | true | Whether dropdown should select new option when using keyboard shortcuts. Setting to false will require enter or left click to confirm a choice. |
forceSelection | false | Whether search selection will force currently selected choice when element is blurred. If a select tag with a required attribute was used, the forceSelection setting will be set to true automatically |
keepSearchTerm | false | Whether the search value should be kept and menu stays filtered on item selection. |
allowCategorySelection | false | Whether menu items with sub-menus (categories) should be selectable |
fireOnInit | false | Whether callbacks should fire when initializing dropdown values |
placeholder | auto |
auto
Convert option with "" (blank string) value to placeholder text
value
Sets string value to placeholder text, leaves "" value
false
Leaves "" value as a selectable option
|
ignoreDiacritics | false | When activated, searches will also match results for base diacritic letters. For example when searching for 'a', it will also match 'á' or 'â' or 'å' and so on...
It will also ignore diacritics for the searchterm, so if searching for 'ó', it will match 'ó', but also 'o', 'ô' or 'õ' and so on... Not available in IE |
Remote Settings
Setting | Default | Description |
---|---|---|
apiSettings | false | Can be set to an object to specify API settings for retrieving remote selection menu content from an API endpoint |
fields |
fields: {
remoteValues : 'results', // grouping for api results
values : 'values', // grouping for all dropdown values
disabled : 'disabled', // whether value should be disabled
name : 'name', // displayed dropdown text
description : 'description', // displayed dropdown description
descriptionVertical : 'descriptionVertical', // whether description should be vertical
value : 'value', // actual dropdown value
text : 'text', // displayed text when selected
type : 'type', // type of dropdown element
image : 'image', // optional image path
imageClass : 'imageClass', // optional individual class for image
icon : 'icon', // optional icon name
iconClass : 'iconClass', // optional individual class for icon (for example to use flag instead)
class : 'class', // optional individual class for item/header
divider : 'divider' // optional divider append for group headers
actionable : 'actionable' // optional actionable item
}
|
List mapping dropdown content to JSON Property when using API |
filterRemoteData | false | Whether results returned from API should be filtered by query before being displayed |
saveRemoteData | true | When enabled, will automatically store selected name/value pairs in sessionStorage to preserve user selection on page refresh. Disabling will clear remote dropdown values on refresh. |
throttle | 200 | How long to wait after last user input to search remotely |
Multiple Select Settings
Setting | Default | Description |
---|---|---|
useLabels | true | Whether multiselect should use labels. Must be set to true when allowAdditions is true |
delimiter |
,
|
When multiselect uses normal input tag, the values will be delimited with this character. Also used as the keyboard shortcut while entering multiple values |
maxSelections | false | When set to a number, sets the maximum number of selections |
headerDivider | true | whether option headers should have an additional divider line underneath when converted from <select><optgroup> |
collapseOnActionable | true | whether the dropdown should collapse upon selection of an actionable item |
label |
label: {
transition : 'scale',
duration : 200,
variation : false
}
|
Allows customization of multi-select labels. Setting transition: false will not animate the label at all |
Additional Settings
Setting | Default | Description |
---|---|---|
direction | 'auto' | When set to auto determines direction based on whether dropdown can fit on screen. Set to upward or downward to always force a direction. |
keepOnScreen | true | Whether dropdown should try to keep itself on screen by checking whether menus display position in its context (Default context is page). |
context | window | Element context to use when checking whether can show when keepOnScreen: true |
fullTextSearch | 'exact' | Specifying to "true" will use a fuzzy full text search, setting to "exact" will force the exact search to be matched somewhere in the string, setting to "false" will only match start of string. |
hideDividers> | false | How to handle dividers in the dropdown while searching. Dividers are defined as all siblings of items that match the divider selector
false
Dividers are not hidden
true
All dividers are automatically hidden
'empty'
All dividers not followed by a visible item are hidden (divider siblings are treated as a group)
|
preserveHTML | true | Whether HTML included in dropdown values should be preserved. (Allows icons to show up in selected value) |
sortSelect | false | Whether to sort values when creating a dropdown automatically from a select element.
true
Sort by name [A, B, C, a, b, c]
natural
Sort by lowercase name [A, a, B, b, C, c]
function(a, b){}
custom sort function is executed
|
showOnFocus | false | Whether to show dropdown menu automatically on element focus. |
allowTab | true | Whether to allow the element to be navigable by keyboard, by automatically creating a tabindex |
transition | auto (slide down / slide up) | Named transition to use when animating menu in and out. Defaults to slide down or slide up depending on dropdown direction. Fade and slide down are available without including ui transitions
Alternatively you can provide an object to set individual values for hide/show transitions as well as hide/show duration
{
showMethod : 'fade',
showDuration : 200,
hideMethod : 'zoom',
hideDuration : 500,
}
|
duration | 200 | Duration of animation events. The value will be ignored when individual hide/show duration values are provided via the transition setting |
displayType | false | Specify the final transition display type (block, inline-block etc) so that it doesn't have to be calculated. |
keys |
keys : {
backspace : 8,
deleteKey : 46,
enter : 13,
escape : 27,
pageUp : 33,
pageDown : 34,
leftArrow : 37,
upArrow : 38,
rightArrow : 39,
downArrow : 40
}
|
The keycode used to represent keyboard shortcuts.
|
delay |
delay : {
hide : 300,
show : 200,
search : 20
}
|
Time in milliseconds to debounce show or hide behavior when on: hover is used, or when touch is used. |
Callbacks
Context | Description | |
---|---|---|
onChange(value, text, $choice) | Dropdown | Is called after a dropdown value changes. Receives the name and value of selection and the active menu element |
onAdd(addedValue, addedText, $addedChoice) | Dropdown | Is called after a dropdown selection is added using a multiple select dropdown, only receives the added value |
onRemove(removedValue, removedText, $removedChoice) | Dropdown | Is called after a dropdown selection is removed using a multiple select dropdown, only receives the removed value |
onActionable(value, text, $choice) | Dropdown | Is called after an actionable item has been selected |
onLabelCreate(value, text) | $label (jQDOM) | Allows you to modify a label before it is added. Expects the jQ DOM element for a label to be returned. |
onLabelRemove(value) | $label (jqDOM) | Called when a label is remove, return false; will prevent the label from being removed. |
onLabelSelect($selectedLabels) | Dropdown | Is called after a label is selected by a user |
onNoResults(searchValue) | Dropdown | Is called after a dropdown is searched with no matching values |
onShow | Dropdown | Is called before a dropdown is shown. If false is returned, dropdown will not be shown. |
onHide | Dropdown | Is called before a dropdown is hidden. If false is returned, dropdown will not be hidden. |
onSearch | Dropdown | Is called before a search takes place to filter the items list. If false is returned, the search and item filtering is cancelled. |
Templates
These templates are used to generate the HTML structures for parts of dropdown
Functions | |
---|---|
templates |
$.fn.dropdown.settings.templates : {
deQuote: function(string) {
// returns removed/replaced double quotes from a string
},
escape: function(string) {
// returns escaped string for injected results
},
dropdown: function (select, fields, preserveHTML, className) {
// returns dropdown HTML from select values
},
menu: function (response, fields, preserveHTML, className) {
// returns menu html from response data
},
label: function (value, text, preserveHTML, className) {
// returns label html for multiselect
},
message: function (message) {
// returns messages like "No results"
},
addition: function (choice) {
// return user addition for selection menu
}
}
|
Module Settings
DOM Settings
DOM settings specify how this module should interface with the DOM
Default | Description | |
---|---|---|
namespace | dropdown | Event namespace. Makes sure module teardown does not effect other events attached to an element. |
message |
You can specify site wide messages by modifying
message: {
addResult : 'Add {term}',
count : '{count} selected',
maxSelections : 'Max {maxCount} selections',
noResults : 'No results found.'
}
|
|
selector |
selector : {
addition : '.addition',
divider : '.divider, .header',
dropdown : '.ui.dropdown',
icon : '> .dropdown.icon',
input : '> input[type="hidden"], > select',
item : '.item',
label : '> .label',
remove : '> .label > .delete.icon',
siblingLabel : '.label',
menu : '.menu',
message : '.message',
menuIcon : '.dropdown.icon',
search : 'input.search, .menu > .search > input',
sizer : '> span.sizer',
text : '> .text:not(.icon)',
unselectable : '.disabled, .filtered',
clearIcon : '> .remove.icon'
}
|
|
regExp |
regExp : {
escape : /[-[\]{}()*+?.,\\^$|#\s]/g,
}
|
|
metadata |
metadata : {
defaultText : 'defaultText',
defaultValue : 'defaultValue',
placeholderText : 'placeholderText',
text : 'text',
value : 'value'
}
|
|
className |
className : {
active : 'active',
addition : 'addition',
animating : 'animating',
description : 'description',
descriptionVertical : 'vertical',
disabled : 'disabled',
empty : 'empty',
dropdown : 'ui dropdown',
filtered : 'filtered',
hidden : 'hidden transition',
icon : 'icon',
image : 'image',
item : 'item',
label : 'ui label',
loading : 'loading',
menu : 'menu',
message : 'message',
multiple : 'multiple',
placeholder : 'default',
sizer : 'sizer',
search : 'search',
selected : 'selected',
selection : 'selection',
text : 'text',
upward : 'upward',
leftward : 'left',
visible : 'visible',
clearable : 'clearable',
noselection : 'noselection',
delete : 'delete',
header : 'header',
divider : 'divider',
groupIcon : '',
unfilterable : 'unfilterable',
actionable : 'actionable'
}
|
|
name | Dropdown | Name used in debug logs |
silent | false | Silences all console output including error messages, regardless of other debug settings. |
debug | false | Provides standard debug output to console |
performance | true | Provides performance stats in console, and suppresses other debug output. |
verbose | false | Provides ancillary debug output to console |
error |
error : {
action : 'You called a dropdown action that was not defined',
alreadySetup : 'Once a select has been initialized behaviors must be called on the created ui dropdown',
labels : 'Allowing user additions currently requires the use of labels.',
missingMultiple : '
|
Taking care of untrusted remote data
Untrusted Data
You should never trust any data and should make sure all data is processed on the server to sanitize before passing it to the client.
However you might want to use existing foreign API services as data storage in your dropdown module. In this case it is recommended to set the preserveHTML
option to false
. Then all data provided by the frontend will be either encoded to use HTML-entities for the most evil characters like &, <, >, ", ', `
or any html data will be completely removed on item selection
Evil API Example
The following dropdown fields are bound to an evil API backend which tries to inject code