Back to Snippets

Autocomplete Search Input JS

Start typing a country and a list of matches appears under the field, with the part you typed highlighted in each one. Arrow keys move through the list, Enter picks the highlighted match, Escape closes the list, and clicking a suggestion fills the field.

The suggestions come from a plain array filtered on every input event and capped at eight results. Each result is rebuilt as a list item with the matching characters wrapped in a mark element, which gives the highlight without fragile string splitting. Keyboard handling tracks an active index, wraps at either end, and mirrors it into aria-activedescendant so a screen reader announces the option the arrows have reached while focus stays in the input.

The markup follows the combobox pattern from the ARIA authoring practices. Swapping the array for a fetch call is a one line change in the filter function.

0
#javascript
#css
#autocomplete
#search
#input
#typeahead
#combobox
#accessibility
#ui