Select
<et2-select> | Et2Select
Select one or more options from a given list
Select or searchbox?
A select hands back the value of the option the user chose. If what you want is the text they typed, you want et2-searchbox instead - the two are compared in Searchbox or select?.
Where the options come from
A select is only as good as its list, and the list can arrive three different ways. They are merged, not
exclusive, so a widget with a built-in list (most of the et2-select-* variants below) still
accepts extra options from either of the other two.
In an eTemplate, the usual source is the sel_options array the server sends with the content.
The widget finds its own entry by id, so nothing has to be written in the template at all:
$sel_options['priority'] = ['1' => 'low', '2' => 'normal', '3' => 'high'];
For a short fixed list that never changes, <option> children in the
.xet file are less work than a server array. The tag’s text is the label, and it is translated:
<et2-select id="priority" label="Priority">
<option value="1">low</option>
<option value="2">normal</option>
<option value="3">high</option>
</et2-select>
From javascript - and in every example on this page, since there is no server here - assign an array of
{value, label} objects to select_options.
Examples
Options
Each option needs at least a value and a label.
<et2-select id="select-basic" label="Priority"></et2-select>
<script>
document.getElementById("select-basic").select_options = [
{value: "1", label: "Low"},
{value: "2", label: "Normal"},
{value: "3", label: "High"}
];
</script>
Value
value is the chosen option’s value, and changing it fires change. A
value that is not in the list is not kept, since there would be no label to show for it: on the first render
the widget falls back to the empty option if there is one, and to the first option if there is not. That is
why a select with no emptyLabel never sits there showing nothing.
Value: ?
<et2-select id="select-value" value="2"></et2-select>
<p>Value: <span id="select-value-output">?</span></p>
<script>
const select = document.getElementById("select-value");
const selectOutput = document.getElementById("select-value-output");
select.select_options = [
{value: "1", label: "Low"},
{value: "2", label: "Normal"},
{value: "3", label: "High"}
];
const showValue = () => {selectOutput.textContent = JSON.stringify(select.value);};
select.addEventListener("change", showValue);
customElements.whenDefined("et2-select").then(() => select.updateComplete).then(showValue);
</script>
Empty label
emptyLabel adds a first option whose value is "", for “no choice made”. Give it a
word that says what empty means here - “All” in a filter, “None” in a form - rather than leaving the reader
to guess.
<et2-select id="select-empty" emptyLabel="All"></et2-select>
<script>
document.getElementById("select-empty").select_options = [
{value: "1", label: "Low"},
{value: "2", label: "Normal"},
{value: "3", label: "High"}
];
</script>
Multiple
multiple lets the user pick more than one. The value becomes an array, and each choice is shown
as a tag.
Value: ?
<et2-select id="select-multiple" multiple></et2-select>
<p>Value: <span id="select-multiple-output">?</span></p>
<script>
const multi = document.getElementById("select-multiple");
const multiOutput = document.getElementById("select-multiple-output");
multi.select_options = [
{value: "phone", label: "Phone"},
{value: "email", label: "Email"},
{value: "fax", label: "Fax"},
{value: "post", label: "Post"}
];
multi.value = ["email", "post"];
const showMulti = () => {multiOutput.textContent = JSON.stringify(multi.value);};
multi.addEventListener("change", showMulti);
customElements.whenDefined("et2-select").then(() => multi.updateComplete).then(showMulti);
</script>
Searching
search adds a field that filters the list as the user types. It is worth adding once the list
is longer than a screen, and pointless below about a dozen options.
<et2-select id="cat_id" label="Category" search="true"/>
search, searchUrl, searchOptions and
allowFreeEntries all come from SelectSearchMixin,
which documents them in full - including how to have the server supply more options as the user types, so
the list never has to be sent in one piece. Several widgets on this page turn search on for
themselves because their lists are always long:
et2-select-country and
et2-select-account among them.
Free entries
allowFreeEntries turns text that matches no option into an option of its own, so the value can
be something you never offered. Type a name and press Enter or comma.
Value: ?
<et2-select id="select-free" multiple allowFreeEntries></et2-select>
<p>Value: <span id="select-free-output">?</span></p>
<script>
const free = document.getElementById("select-free");
const freeOutput = document.getElementById("select-free-output");
free.select_options = [
{value: "red", label: "Red"},
{value: "green", label: "Green"},
{value: "blue", label: "Blue"}
];
free.addEventListener("change", () => {freeOutput.textContent = JSON.stringify(free.value);});
</script>
Editing a free entry
editModeEnabled lets the user correct a tag they typed by double-clicking it, instead of
removing it and typing the whole thing again. It only applies to free entries, so
allowFreeEntries has to be on too.
<et2-select id="select-edit" multiple allowFreeEntries editModeEnabled></et2-select>
<script>
const edit = document.getElementById("select-edit");
edit.select_options = [{value: "red", label: "Red"}, {value: "green", label: "Green"}];
edit.value = ["mauve"];
</script>
Placeholder, help text and clearing
placeholder is a hint shown while nothing is selected - unlike emptyLabel it is
not an option, so it cannot be chosen. helpText explains the field below it, and
clearable adds an X to get back to no selection.
The help text’s attribute is help-text, not helpText. Both work from a
.xet template, where eTemplate maps the camelCase name for you; plain HTML like the preview
below only has the real attribute.
<et2-select id="select-extras" label="Priority" placeholder="Not set yet"
help-text="How soon this needs doing" clearable></et2-select>
<script>
document.getElementById("select-extras").select_options = [
{value: "1", label: "Low"},
{value: "2", label: "Normal"},
{value: "3", label: "High"}
];
</script>
Icons and titles
An option can carry an icon, using the same image names as
et2-image, and a title that becomes its tooltip.
<et2-select id="select-icons" value="email"></et2-select>
<script>
document.getElementById("select-icons").select_options = [
{value: "phone", label: "Phone", icon: "telephone", title: "Call them"},
{value: "email", label: "Email", icon: "envelope", title: "Write to them"},
{value: "post", label: "Post", icon: "printer", title: "Print and mail it"}
];
</script>
Groups
An option with a children array becomes a heading with its own options under it, rather than a
selectable option itself - so do not leave the value to default, or it lands on a heading that cannot be
displayed.
<et2-select id="select-groups" value="email"></et2-select>
<script>
document.getElementById("select-groups").select_options = [
{
value: "electronic", label: "Electronic", children: [
{value: "phone", label: "Phone"},
{value: "email", label: "Email"}
]
},
{
value: "paper", label: "On paper", children: [
{value: "fax", label: "Fax"},
{value: "post", label: "Post"}
]
}
];
</script>
Disabled and readonly
disabled means “not right now” and can be turned off again from javascript.
readonly shows the value without allowing any change and submits nothing. See
Disabled vs Readonly vs Hidden.
<et2-select id="select-disabled" value="2" disabled></et2-select>
<et2-select id="select-readonly" value="2" readonly></et2-select>
<script>
const options = [
{value: "1", label: "Low"},
{value: "2", label: "Normal"},
{value: "3", label: "High"}
];
document.getElementById("select-disabled").select_options = options.slice();
document.getElementById("select-readonly").select_options = options.slice();
</script>
Variants
Most of the time you do not want a plain et2-select at all, but one of the variants that brings
its own list. They all take everything on this page - only the list, and the one or two attributes that
shape it, are different.
| et2-select-access | private / group public / global public |
| et2-select-account | users and groups |
| et2-select-app | installed applications |
| et2-select-bitwise | a set of flags stored as one integer |
| et2-select-bool | yes / no |
| et2-select-cat | categories, as a tree |
| et2-select-country | countries, with flags |
| et2-select-day | day of the month, 1 – 31 |
| et2-select-dow | days of the week |
| et2-select-hour | hour of the day |
| et2-select-lang | installed languages |
| et2-select-month | January - December |
| et2-select-number | a range of numbers |
| et2-select-percent | 0% - 100% |
| et2-select-priority | low / normal / high |
| et2-select-state | states or provinces of one country |
| et2-select-tab | an application, or one of its tabs |
| et2-select-thumbnail | images, shown as thumbnails |
| et2-select-timezone | timezones |
| et2-select-year | years around this one |
Slots
| Name | Description |
|---|---|
| (default) |
Reflected into listbox options. Must be sl-option elements. You can use
sl-divider to group items visually. Normally you set the options by parameter.
|
prefix
|
Used to prepend a presentational icon or similar element to the combobox. |
help-text
|
Text that describes how to use the input. Alternatively, you can use the
help-text attribute.
|
Learn more about using slots.
Properties
| Name | Description | Reflects | Type | Default |
|---|---|---|---|---|
clearable
|
Adds a clear button when the select is not empty. |
boolean
|
false
|
|
editModeEnabled
|
Allow editing tags by clicking on them. allowFreeEntries must be true. Tag editing lives here rather than in SelectSearchMixin: it reuses the search container but is not search, and it needs Et2Tag, which only Et2Select has. |
boolean
|
false
|
|
multiple
|
Allows more than one option to be selected. |
|
boolean
|
false
|
onTagClick
|
Click handler for individual tags instead of the select as a whole. Only used if multiple=true so we have tags |
any
|
- | |
placeholder
|
Placeholder text to show as a hint when the select is empty. |
string
|
''
|
|
placement
|
The preferred placement of the select’s menu. Note that the actual placement may vary as needed to keep the listbox inside of the viewport. |
|
'top' | 'bottom'
|
'bottom'
|
tagTag
|
Tag used for rendering tags when multiple=true Used for creating, finding & filtering options. |
StaticValue
|
- |
Learn more about attributes and properties.
Inherited properties (26)
Et2Widget
| Name | Description |
|---|---|
accesskey |
Accesskey provides a hint for generating a keyboard shortcut for the current element. The attribute value must consist of a single printable character. |
actions |
Set Actions on the widget Each action is defined as an object: move: { type: “drop”, acceptedTypes: “mail”, icon: “move”, caption: “Move to” onExecute: javascript:mail_move” } This will turn the widget into a drop target for “mail” drag types. When “mail” drag types are dropped, the global function mail_move(egwAction action, egwActionObject sender) will be called. The ID of the dragged “mail” will be in sender.id, some information about the sender will be in sender.context. The etemplate2 widget involved can typically be found in action.parent.data.widget, so your handler can operate in the widget context easily. The location varies depending on your action though. It might be action.parent.parent.data.widget To customise how the actions are handled for a particular widget, override _link_actions(). It handles the more widget-specific parts. |
align |
Used by Et2Box to determine alignment. Allowed values are left, right |
class |
CSS Class. This class is applied to the outside, on the web component itself. Due to how WebComponents work, this might not change anything inside the component. |
data |
Set the dataset from a CSV |
deferredProperties |
Any attribute that refers to row content cannot be resolved immediately, but some like booleans cannot stay a string because it’s a boolean attribute. We store them for later, and parse when they’re fully in their row. If you are creating a widget that can go in a nextmatch row, and it has boolean attributes that can change for each row, add those attributes into deferredProperties |
disabled |
Disables the select control. |
dom_id |
Get the actual DOM ID, which has been prefixed to make sure it’s unique. |
hidden |
The widget is not visible. As far as the user is concerned, the widget does not exist. Widgets hidden with an attribute in the template may not be created in the DOM, and will not return a value. Widgets can be hidden after creation, and they may return a value if hidden this way. |
id |
Get the ID of the widget |
label |
The select’s label. If you need to display HTML, use the label slot instead. |
noLang |
Disable any translations for the widget |
parentId |
Parent is different than what is specified in the template / hierarchy. Widget ID of another node to insert this node into instead of the normal location |
statustext |
Tooltip which is shown for this element on hover |
styles |
WebComponent * |
options |
Get property-values as object |
supportedWidgetClasses |
et2_widget compatability |
Et2InputWidget
| Name | Description |
|---|---|
autofocus |
Have browser focus this input on load. Overrides etemplate2.focusOnFirstInput(), use only once per page https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attributes |
hasFeedbackFor |
Get a list of feedback types |
helpText |
The select’s help text. If you need to display HTML, use the help-text slot instead.
|
needed |
Compatibility for deprecated name “needed” |
Et2WidgetWithSelect
| Name | Description |
|---|---|
emptyLabel |
Textual label for first row, eg: ‘All’ or ‘None’. It’s value will be ″ |
select_options |
Select box options Will be found automatically based on ID and type, or can be set explicitly in the template using |
translate |
List of properties that get translated |
_optionTargetNode |
Get the node where we’re putting the options If this were a normal selectbox, this would be just the |
LitElement
| Name | Description |
|---|---|
updateComplete |
A read-only promise that resolves when the component has finished updating. |
Events
| Name | Description | Event Detail |
|---|---|---|
change |
Emitted when the control’s value changes. |
Event
|
sl-clear |
Emitted when the control’s value is cleared. | - |
sl-input |
Emitted when the control receives input. | - |
sl-focus |
Emitted when the control gains focus. | - |
sl-blur |
Emitted when the control loses focus. | - |
sl-show |
Emitted when the suggestion menu opens. | - |
sl-after-show |
Emitted after the suggestion menu opens and all animations are complete. | - |
sl-hide |
Emitted when the suggestion menu closes. | - |
sl-after-hide |
Emitted after the suggestion menu closes and all animations are complete. | - |
Learn more about events.
Methods
| Name | Description | Arguments |
|---|---|---|
blur()
|
Removes focus from the control. | - |
filterOutMissingOptions()
|
Check a value for missing options and remove them. We’ll warn about it in the helpText, and if they save the change will be made. This is to avoid the server-side validation error, which the user can’t do much about. |
value: string[]
|
hide()
|
Hides the listbox. | - |
show()
|
Shows the listbox. | - |
startEdit()
|
Start editing the current value if multiple=false |
tag: Et2Tag
|
Learn more about methods.
Inherited methods (32)
Et2Widget
| Name | Description |
|---|---|
checkCreateNamespace() |
Checks whether a namespace exists for this element in the content array. If yes, an own perspective of the content array is created. If not, the parent content manager is used. Constructor attributes are passed in case a child needs to make decisions |
clone() |
Creates a copy of this widget. |
createElementFromNode() |
Create a et2_widget from an XML node. First the type and attributes are read from the node. Then the readonly & modifications arrays are checked for changes specific to the loaded data. Then the appropriate constructor is called. After the constructor returns, the widget has a chance to further initialize itself from the XML node when the widget’s loadFromXML() method is called with the node. |
getArrayMgr() |
Returns the array manager object for the given part |
getArrayMgrs() |
Returns an associative array containing the top-most array managers. |
getChildren() |
Get child widgets Use |
getInstanceManager() |
Returns the instance manager |
getPath() |
Returns the path into the data array. By default, array manager takes care of this, but some extensions need to override this |
getRoot() |
Returns the base widget Usually this is the same as getInstanceManager().widgetContainer |
loadingFinished() |
Needed for legacy compatability. |
parseXMLAttrs() |
The parseXMLAttrs function takes an XML DOM attributes object and adds the given attributes to the _target associative array. This function also parses the legacyOptions. N.B. This is only used for legacy widgets. WebComponents use transformAttributes() and do their own handling of attributes. |
set_label() |
NOT the setter, since we cannot add to the DOM before connectedCallback() TODO: This is not best practice. Should just set property, DOM modification should be done in render https://lit-element.polymer-project.org/guide/templates#design-a-performant-template |
setArrayMgr() |
Sets the array manager for the given part |
setArrayMgrs() |
Sets all array manager objects - this function can be used to set the root array managers of the container object. |
setInstanceManager() |
Set the instance manager Normally this is not needed as it’s set on the top-level container, and we just return that reference |
_handleClick() |
Click handler calling custom handler set via onclick attribute to this.onclick |
set_class() |
Set the widget class |
set_disabled() |
Wrapper on this.disabled because legacy had it. |
set_statustext() |
supports legacy set_statustext |
Et2InputWidget
| Name | Description |
|---|---|
et2HandleFocus() |
When input receives focus, clear any validation errors. If the value is the same on blur, we’ll put them back The ones from the server (ManualMessage) can interfere with submitting. Named et2HandleFocus to avoid overwriting handleFocus() in Shoelace components |
focus() |
Sets focus on the control. |
getInputNode() |
Get input to e.g. set aria-attributes |
handleSlChange() |
Handle sl-change event from Shoelace components and dispatch a change event so anything listening for change events can react to it instead of having to listen for both sl-change and change. |
isValid() |
Used by etemplate2 to determine if we can submit or not |
submit() |
Called whenever the template gets submitted. We return false if the widget is not valid, which cancels the submission. |
validate() |
Massively simplified validate, as compared to what ValidatorMixin gives us, since ValidatorMixin extends FormControlMixin which breaks SlSelect’s render() We take all validators for the widget, and if there’s a value (or field is required) we check the value with each validator. For array values we check each element with each validator. If the value does not pass the validator, we collect the message and display feedback to the user. We handle validation errors from the server with ManualMessages, which always “fail”. If the value is empty, we only validate if the field is required. |
_oldChange() |
Change handler calling custom handler set via onchange attribute |
Et2WidgetWithSelect
| Name | Description |
|---|---|
loadFromXML() |
Additional customisations from the XET node |
optionSearch() |
Search options for a given value, returning the first matching option |
_emptyLabelTemplate() |
Used for the “no value” option for single select Placeholder is used for multi-select with no value |
destroy() |
et2_widget compatability |
set_select_options() |
Set select options |
Parts
| Name | Description |
|---|---|
prefix |
The container that wraps the prefix slot. |
tags |
The container that houses option tags when multiselect is used. |
display-input |
The element that displays the selected option’s label, an element. |
expand-icon |
The container that wraps the expand icon. |
combobox |
The container the wraps the prefix, combobox, clear icon, and expand button. |
listbox |
The listbox container where options are slotted. |
option |
The options in the listbox container |
icon |
Icon in the option |
emptyLabel |
Wrapper around the label shown when there is no option selected |
tag__prefix |
The container that wraps the option prefix |
tag__suffix |
The container that wraps the option suffix |
tag__limit |
Element that is shown when the number of selected options exceeds maxOptionsVisible |
Learn more about customizing CSS parts.