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.
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.
<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>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}`);
});chosen: GhanaThe 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.