Overview
An autocomplete is a text field with autocomplete="on" on its input and data-url on its container. The URL returns JSON. As the user types, a menu under the field lists the results that match, with the typed text marked. A pick writes the result’s text into the field. The script builds the menu, so the markup is a plain form field.
Pick another component when:
- the user picks several values: Multiselect
- the user types free values as chips: Tag Input
- the list is short and fixed: a select in Forms
Markup
Variants
The canon carries data-fetch="once" because the demo data is a static file. For a server that searches, use each: see Fetch Modes.
| Group | Option | Markup | On element | Use |
|---|---|---|---|---|
| Min characters | 3 (default) | — | — | The search starts at the third character |
| Min characters | 2 | [data-min-chars="2"] |
.nds-form-container |
For short names, such as people’s names |
| Min characters | 1 | [data-min-chars="1"] |
.nds-form-container |
For a short list loaded once, such as cities |
| Min characters | 0 (hint: A click shows the whole list) | [data-min-chars="0"] |
.nds-form-container |
A click or the Down Arrow shows the whole list before the user types, and typing filters it. For a short list loaded once, such as services |
| Row | Meta line (hint: The service group under each name) | canon #autocomplete-row |
.nds-form-container |
Each row shows more fields of its result under the name, here a Meta line. The match is marked in the name only |
| Strict | Strict (hint: Accepts only a value picked from the list) | [data-strict] |
.nds-form-container |
The form accepts only text the user picked from the list, and the menu shows “No results” when nothing matches. Not for a search field, where any text is a valid search |
| Custom empty message | Custom empty message (hint: Replaces the “No results” text) | [data-empty-message="No matching services"] |
.nds-form-container[data-strict] |
Replaces the “No results” text that a strict field shows when nothing matches |
| Posted value | Result id (hint: Posts the picked result’s id) | [data-value-field="Id"] |
.nds-form-container |
A pick writes the result’s Id into the named hidden input. Write this row and the next. Write Strict too when the server needs the id |
| Posted value | Result id (hint: Posts the picked result’s id) | canon #autocomplete-value |
.nds-form-control |
The named hidden input that holds the id |
| Required | Required (hint: Press Validate with the field empty) | [data-required] |
.nds-form-container |
The form needs text in the field. Use it when the field is required |
| Field states | Label, info, feedback, required | — | — | Shared by every form field. See Forms |
Behavior
Fetch Modes
With data-fetch="each", the default, the script requests data-url with the typed text on each search, such as services.json?q=visa. The server filters the results. With data-fetch="once", the script requests data-url once, with no query, and keeps the list. On each search, it shows the results whose data-display-field field holds the typed text, in any letter case.
Strict Mode
data-strict on the container makes the form accept only a picked result. At submit, the field shows “Choose from the suggestions” when its text is not the last pick. Typed text that matches a result exactly still fails until the user picks it. An empty field passes, so add data-required to the container when the field is required. Text that the server writes into the field counts as picked, so it still passes after the user focuses the field.
When nothing matches, a strict field’s menu stays open and shows “No results”, in Arabic on an Arabic page. A screen reader reads the message. Without data-strict, any typed text is valid, so the menu closes instead.
Posted Value
By default, the form posts the text in the field. To post another field of the result, such as its id, add data-value-field to the container and write a named hidden input in the .nds-form-control. Text that is not a pick empties the hidden input, so a changed or emptied field never posts an old id. Leave name off the text input when the server takes the id alone. To show a saved pick, write its text in the text input’s value and its id in the hidden input’s value. To pick a result from a script, such as a city that a postcode sets, call NDS.Autocomplete.selectItem(el, item).
Search Box
When the autocomplete is in a .nds-search-box, a pick also clicks the box’s .nds-search-btn. The search then runs with the picked text, and the user does not click Search again.
Built-in Features
-
Auto-initialization
A field starts on its first focus, before the user types. A field added to the page later needs no init call.
-
Result Highlighting
The typed text is marked in each result with
<mark>. The menu shows the first 20 results. -
Keyboard Navigation
The arrow keys move through the results and wrap at the ends. Home and End go to the first and the last result, and the result the keys reach scrolls into view. Enter picks it. Escape and Tab close the menu with no pick.
-
Debounced Fetching
A search starts 300 ms after the last keystroke. A new search cancels the request before it. A spinner replaces the clear button while a request runs. When a request fails, the menu shows "Could not load suggestions" and a screen reader reads it. The next focus on the field tries the request again. Results that arrive after the user left the field do not open the menu.
-
Screen Reader Support
The input is a combobox, and the menu is a listbox of options. A screen reader reads the result the arrow keys reach while focus stays in the input.
-
Clear Button
The clear button empties the field, drops the last pick and closes the menu. It fires
nds:autocomplete:clear. -
Menu Placement
The menu is as wide as the field. In a drawer, a modal or another scroll area that would cut it off, the menu moves to
<body>while it is open.
Best Practices
- Use
data-fetch="once"for a list of a few hundred items or fewer, such as cities or departments. Useeachfor a large set that the server searches. - Lower
data-min-charsonly when a short query gives a useful list. Witheach, a lower number sends more requests. - Use
data-min-chars="0"withdata-fetch="once"anddata-strictwhen the user picks one item of a short list, such as a service: a click shows them all, and typing narrows them. Do not add a search box to the menu: the field is the search box. - Use a row template for a fact the user picks by, such as how long a service takes or its department. Keep it to one line under the name.
- Use
data-strictwhen the form accepts only a picked result. Leave it off a search field. - Use
data-value-fieldwithdata-strictwhen the server takes a code or an id, such as a city code.data-strictalone still posts the text. - Write the placeholder or the info text as a hint of what to type, such as “Type part of a service name”.
- For the label, info text, feedback and the required mark, see Forms. They work the same on every field.
API
Other Classes
| Class | Element | Effect |
|---|---|---|
.nds-autocomplete-menu |
the menu | The script adds the menu, with .nds-dropmenu-menu, in the .nds-form-control. Style the menu through this class: it stays on the menu when the menu moves to <body> |
.nds-autocomplete-row |
a <template> in the .nds-form-container |
The parts of each row. The script copies it for each result and fills its data-field elements. Without it, a row shows the data-display-field field alone |
.nds-option-text |
each row from the template | The script wraps the copied parts in it, so they stack under the name and the row grows to fit them |
.nds-autocomplete-value |
a hidden <input> |
The script adds it with data-strict. It holds the picked text, or the text already in the field when the field builds. It has no name, so the form data does not change |
Data Attributes
| Attribute | Element | Effect |
|---|---|---|
data-url |
.nds-form-container |
The URL that returns the JSON results. Required, unless create() gets the items option. It may hold a query string: the script then adds the typed text after & |
data-display-field |
.nds-form-container |
The result field that each row shows and that a pick writes into the input. The default is Title |
data-value-field |
.nds-form-container |
The result field that a pick writes into the named hidden input in the .nds-form-control. selectItem() writes it too. Typing, the clear button, clear() and setValue() with new text empty that input. A form reset puts back the value it held when the field started. These writes fire no event of their own: the text input fires input and change. With data-strict, text beside an empty hidden input fails |
data-field |
an element in the .nds-autocomplete-row template |
The result field the script writes into it, as text. In the data-display-field field, the match is marked. A field with no value removes its element, or the whole .nds-meta-item around it. renderItem(), when you pass it, replaces the template |
data-fetch |
.nds-form-container |
each (the default) requests the URL on each search. once requests it once and filters in the browser |
data-min-chars |
.nds-form-container |
The fewest characters that start a search. The default is 3. Shorter text closes the menu. 0 shows the whole list on a click or the Down Arrow, and again when the user deletes the text. On a field that holds a pick, the list shows every item, with the pick active |
data-query-param |
.nds-form-container |
The name of the query parameter that holds the typed text with each. The default is q |
data-results-path |
.nds-form-container |
A dot path to the results array in the response, such as response.items. Without it, the script reads an array, or the results or data key of an object |
data-empty-message |
.nds-form-container with data-strict |
The text when nothing matches. The default is “No results”, in Arabic on an Arabic page. See Strict Mode |
data-empty-icon |
.nds-form-container with data-strict |
The icon classes when nothing matches. The default is nds-icon nds-hgi-search-01 |
data-strict |
.nds-form-container |
The form accepts only a picked result. See Strict Mode above |
data-state~="loading" |
.nds-form-container |
The script sets it when a request starts, and removes it when the latest request ends. The forms script shows a spinner in .nds-form-action |
autocomplete="on" |
the <input> |
Marks the input. The script sets it to off when the field starts, so the browser shows no list of its own, and destroy() sets it back |
data-state~="active" |
a result in the menu | The script sets it on the result that the arrow keys reach, and removes it when they move on |
Tokens
Set a token at :root, or on a wrapper to reach every autocomplete inside it. Give a token with a Dark mode value a dark override too: see Tokens. The highlight is the background of the matched text in a suggestion.
Source: the autocomplete group in _sass/tokens/_components.scss.
| Token | Preview | Value |
|---|---|---|
--autocomplete-highlight | var(--background-mark)Dark mode var(--colors-primary-alpha-50) |
Response Format
The response is a JSON array of objects, or an object that holds the array. Each object needs the data-display-field field. Other fields reach the select event in item.
JavaScript
The NDS.Autocomplete script loads after the page shows. Until it loads, each call loads it and returns a promise of the result, so await a call whose result you use.
| Method | Effect |
|---|---|
NDS.Autocomplete.init() |
Starts the page listener, once. The loader calls it |
NDS.Autocomplete.create(container, options) |
Starts one field now: pass its .nds-form-container. Use it to pass options, or for a field that code searches before the user focuses it. Returns the running instance when the field has already started, and null when it has no input. Call it before the first focus: a started field ignores the options |
NDS.Autocomplete.validate(el, options) |
Checks a data-strict field and returns { valid, message, picked }. Pass { showMessage: false } to check without a message |
NDS.Autocomplete.getValue(el) |
Returns the text in the input, or '' when the field is not found. el is the .nds-form-container, its input, its id or a selector |
NDS.Autocomplete.setValue(el, text) |
Writes the text as a user does, with no fetch and no menu. Returns true, or false when the field is not found. A data-strict field accepts text that matches no pick, and validation reports it as it does for typed text |
NDS.Autocomplete.selectItem(el, item) |
Picks item, a result object, as a user does: writes its data-display-field text and its data-value-field value, and fires input, change and nds:autocomplete:select. It does not move focus, and a search box does not submit. Returns true, or false when the field or item is missing |
NDS.Autocomplete.clear(el) |
Empties the field and forgets the pick |
container.ndsAutocomplete.getValue(), .setValue(text), .selectItem(item), .clear() |
The same, on a field that has started |
NDS.Autocomplete.destroy(container) |
The same as instance.destroy() for the field in container |
instance.destroy() |
Removes the menu, the listeners and .nds-autocomplete-value. A hidden input you wrote stays, with its value. A role or aria-* attribute you wrote on the input stays. The field starts again on its next focus |
| Option | Default | Effect |
|---|---|---|
filter(items, query) |
a match in the data-display-field field |
Returns the results to show. It runs in both fetch modes: with each, on the server’s results |
renderItem(item, query) |
the data-display-field field, with the match marked |
Returns the HTML of one row. The script inserts it as HTML, so escape the text yourself. The match is not marked: add <mark> yourself if you need it |
items |
none | The results your page already holds, in place of data-url. Pass an array, or a function that returns one: the script calls it on each search, so it can return the list for the page language. The field needs no data-url, and it searches the list as data-fetch="once" does |
| Event | Fired on | Detail |
|---|---|---|
nds:autocomplete:fetch |
.nds-form-container, and it bubbles |
{ query, results }, after each list renders. results holds every match, not only the first 20 |
nds:autocomplete:select |
.nds-form-container, and it bubbles |
{ item, text }, after a pick, by a user or by selectItem(). item is the whole result object. text is its data-display-field value, now in the input |
nds:autocomplete:clear |
.nds-form-container, and it bubbles |
{}, after the clear button empties the field |
nds:autocomplete:error |
.nds-form-container, and it bubbles |
{ query, error }, after a data-url request fails. error is the error’s message. preventDefault() stops the “Could not load suggestions” message, for a page that shows its own |
The full API is in the banner of _js/nds-autocomplete.js.