3.0 KiB
title | taxonomy | process | never_cache_twig | ||||
---|---|---|---|---|---|---|---|
Selections |
|
|
true |
When an option is selected from the dropdown menu, Select2 will display the selected value in the container box. By default, it will display the text
property of Select2's internal representation of the selected option.
Templating
The appearance of selected results can be customized by using the templateSelection
configuration option. This takes a callback that transforms the selection data object into a string representation or jQuery object:
You may find it helpful to use a client-side templating engine like Handlebars to define your templates.
Built-in escaping
By default, strings returned by templateSelection
are assumed to contain only text and will be passed through the escapeMarkup
function, which strips any HTML markup.
If you need to render HTML with your selection template, you must wrap your rendered selection in a jQuery object. In this case, the selection will be passed directly to jQuery.fn.append
and will be handled directly by jQuery. Any markup, such as HTML, will not be escaped and it is up to you to escape any malicious input provided by users.
Anything rendered as a selection is templated. This includes placeholders and pre-existing selections that are displayed, so you must ensure that your templating functions can support them.
Limiting the number of selections
Select2 multi-value select boxes can set restrictions regarding the maximum number of options that can be selected. The select below is declared with the multiple
attribute with maximumSelectionLength
in the select2 options.
Clearable selections
You can allow users to clear their current selections with the allowClear
option when initializing Select2. Setting this option to true
will enable an "x" icon that will reset the selection to the placeholder.
$('select').select2({
placeholder: 'This is my placeholder',
allowClear: true
});