Skip to main content
Login

Sign in to access your account

Autocomplete - National Design System

A text field that shows matching results from a JSON source as the user types

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

Preview
<div class="nds-form-container" data-url="../docs-assets/data/services-autocomplete.json" data-display-field="Title" data-fetch="once"> <div class="nds-form-header"> <label for="service-search"> <span class="nds-label">Service</span> <span class="nds-info">Type part of a service name, such as "visa"</span> </label> </div> <div class="nds-form-control"> <i class="nds-icon nds-hgi-search-01" aria-hidden="true"></i> <input type="text" id="service-search" name="service" class="nds-input" autocomplete="on" placeholder="Search services"> <div class="nds-form-action"> <button class="nds-btn nds-subtle nds-clear nds-icon-only" type="button" aria-label="Clear input" data-i18n-aria-label="form.clear_input" hidden> <i class="nds-icon nds-hgi-cancel-01" aria-hidden="true"></i> </button> </div> </div> </div>

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).

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. Use each for a large set that the server searches.
  • Lower data-min-chars only when a short query gives a useful list. With each, a lower number sends more requests.
  • Use data-min-chars="0" with data-fetch="once" and data-strict when 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-strict when the form accepts only a picked result. Leave it off a search field.
  • Use data-value-field with data-strict when the server takes a code or an id, such as a city code. data-strict alone 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.

TokenPreviewValue
--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.

// GET services.json?q=visa [ { "Id": 7, "Title": "Visa Application", "Category": "Travel" }, { "Id": 21, "Title": "Visit Visa Extension", "Category": "Travel" } ]

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
var field = document.querySelector('#service-search').closest('.nds-form-container'); // Keep the picked service for page code. A pick fires input, then select. Typing, the clear button, clear() and setValue() fire input alone. A form reset fires neither, so reset the variable there too var service = null; field.querySelector('.nds-input').addEventListener('input', function () { service = null; }); field.addEventListener('nds:autocomplete:select', function (e) { service = e.detail.item; }); // Match the start of the name only, and show the category in each row NDS.Autocomplete.create(field, { filter: function (items, query) { return items.filter(function (item) { return item.Title.toLowerCase().indexOf(query.toLowerCase()) === 0; }); }, renderItem: function (item) { return NDS.escapeHtml(item.Title) + ' · ' + NDS.escapeHtml(item.Category); } });

The full API is in the banner of _js/nds-autocomplete.js.

Last Modified Date: 16/11/2026 - 09:13 PM
Was this page useful?
60% of users said Yes from 2843 Feedbacks