Easy autocomplete/suggestions for inputs with the HTML5 datalist tag
Sometimes you would like to suggest some options to a user as they type something into an input. Maybe there are popular search categories or tags that people are looking for. You could, of course, implement an API driven feature, or if you want to get a quick way for it to be up and running why not just use the datalist
tag?
In case you want to watch me mess around with the datalist
tag you can watch it here or else keep scrolling to read.
The HTML
<datalist>
element contains a set of<option>
elements that represent the permissible or recommended options available to choose from within other controls. — MDN
Datalist acts as a hybrid between a normal input and a select field where it allows users to either choose a suggested option, see suggestions as you type, or add in your own option.
So how does it work?
Let’s show you how to add the datalist
tag to a regular old <input type="text">
as a simple example (and probably the most common one you will use).
datalist
will work nearly identically to a select
tag taking inner options
.
<input type="text" id="programming_language" list="languages"/>
<datalist id="languages">
<option value="JavaScript"></option>
<option value="Python"></option>
<option value="Java"></option>
<option value="HTML">Stop being a troll</option>
</datalist>
The important thing you will see here is that our input
takes a list
as an option that directs to the id
of the datalist
you want to use to populate the input.
You can also add in some inner notes so in this example you will see if someone starts typing “Html” as their favorite programming language, we can show a little note telling them to stop trolling us…