The HTML datalist tag for filter search

To create a basic dropdown with filter search we normally think of using HTML with JavaScript, where we would listen to the input change events and render a list of recommended values.

HTML provides a tag <datalist> that comes with the inbuilt functionality of filter search and it saves a lot of JavaScript codes.

<label for="select-animal">Who is the strongest animal?:</label>
<input list="animals" id="select-animal" placeholder="type here..." />

<datalist id="animals">
    <option value="Elephant">
    <option value="Tiger">
    <option value="Zebra">
    <option value="Lion">
    <option value="Rabbit">
    <option value="Bear">
    <option value="Monkey">
    <option value="Horse">
    <option value="Rhino">
    <option value="Giraffe">
</datalist>
Result
 

The <datalist> tag requires a set of <option> tags with values. We need to bind the <datalist> to an <input> element, so that when the user types on <input> element the recommended values will be shown.

To bind the <datalist> with <input> element, we need an attribute named list on the <input> element whose value should be the same as the id of the <datalist> element.

The <input> element will hold the selected option, so we can use the vanilla JavaScript to get the selected value from <input> element.

const inputElem = document.getElementById('select-animal');
console.log(inputElem.value); // prints the selected search option

Difference between <datalist> and <select> tag

  • The <datalist> tag shows a list of possible options that match the input text whereas the <select> tag shows the only possible options that the user can select.
  • In the <datalist> tag, the user can select any of the options, or they can input a different value than the available options whereas in the <select> tag the user can only select among the available options and cannot enter any different value.
  • In the <datalist> tag, as the user keeps typing, the options get filtered and only show the options that match the input text, whereas in the <select> tag we cannot filter the available options instead if we have a large list of options then we have to scroll and select the required option.

See Next

2 thoughts on “The HTML datalist tag for filter search

Leave a Reply

Your email address will not be published. Required fields are marked *