Add An Autocomplete Feature with HTML5 Datalist
datalist in HTML is like a combination of both
select elements in that it allows user input and displays a drop-down list of options. The key difference with a
datalist is that, as you type in the field, the available selections begin to filter out based on your input, allowing the ability to autocomplete your selection.
The great thing about the
datalist element, and unlike a
select drop-down, is that the options available in the list are not required. You can input anything you would like and proceed without making a selection from the pre-defined list of options.
Let's write up some quick code that allows a user to select their favorite flavor of ice cream:
<label>What is your favoriate ice cream flavor?</label>
<input list="ice-cream" />
Here, we're presented with a label that asks for the user's favorite ice cream flavor, an input field where they'll either input or select their favorite flavor, and a
datalist element with pre-defined options that they can filter through.
datalistelement actually shows a native control element within the browser, it unfortunately cannot have custom styling applied to it at this time.
That's pretty much all there is to it! HTML's
datalist tag allows for selection and autocompletion of pre-defined options in a list, but does not require the user to make those selections.
Support for HTML's
datalist tag is available in all major browsers and works well on mobile devices, so try it out in your next web application!
Created: January 16, 2022
There are no comments yet. Start the conversation!