Skip to content
jshacks.dev
Browser

Build an autocomplete with a datalist

Add suggestions to a text input with the datalist element, which gives autocomplete and keyboard navigation without any JavaScript library.

1 min read
Summarize in AI

For a field that suggests but does not force a choice, <datalist> gives you a native autocomplete list. It filters as the visitor types and works with the keyboard.

country.htmlHTML
<label for="country">Country</label>
<input id="country" list="countries">
<datalist id="countries">
  <option value="Germany"></option>
  <option value="Ghana"></option>
  <option value="Greece"></option>
</datalist>
country.jsJavaScript
const input = document.querySelector('#country');
const list = document.querySelector('#countries');

input.addEventListener('change', () => {
  const known = [...list.options].some((option) => option.value === input.value);
  console.log(known ? `chosen: ${input.value}` : `custom: ${input.value}`);
});
Text
chosen: Ghana

The list attribute on the input points to the id of the datalist. Typing "G" shows all three options, and typing "Gh" narrows it to Ghana. Because the user can still type anything, the code checks the value against the options and treats a miss as custom input. See the datalist element.

To fill the options from an API, replace the children of the datalist when results arrive. Styling is limited and varies by browser, and screen reader support is uneven, so use a custom combobox if you need full control.

Share

More snippets

APIs

Send JSON with fetch POST

Send a JSON body with fetch POST by stringifying the object and setting the Content-Type header, since fetch does not do either of those for you.

1 min read
APIs

Fetch JSON and handle HTTP errors

Fetch JSON in the browser or Node.js 24 and throw on 404 or 500 yourself, because fetch only rejects on network failure and does not check the status.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.