Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to add suggestions to an input field

Short answer

Create a <datalist> with the options and link it to the field with the list attribute:

<label>
  City
  <input list="cities" name="city">
</label>
 
<datalist id="cities">
  <option value="Berlin">
  <option value="London">
  <option value="Paris">
  <option value="Prague">
</datalist>

Click the field or start typing "P" — the browser shows the matching options. Any other city can still be entered.

Not only text

<datalist> works with different field types. On a slider the options become marks on the scale, on a color field — a ready palette:

<input type="color" list="brand" value="#4682b4">
<datalist id="brand">
  <option value="#4682b4"><option value="#2e8b57"><option value="#ff6347">
</datalist>

datalist or select

<select> allows choosing only one of the listed options. <datalist> only suggests, and anything can be typed. If the value must come from the list — a clothing size, for example — use <select>.

Common mistake

The list attribute does not match the id of <datalist>, or contains a selector like #cities. No link is made, and the suggestions simply do not appear, without any error. list takes exactly the id value, without the hash.

Functions used in this recipe

  • <datalist> — A list of suggestions for a text field: pick an option or type your own.
  • <input> — An input field; its kind is set by the `type` attribute.
  • <option>, <optgroup> — An item of a `<select>` or `<datalist>`; `<optgroup>` puts items into groups.
  • <select> — A drop-down list of options.

Thanks for reading!

Donate to the site — we work hard for you.