HTML datalist Tag Tutorial

In this section, we will learn what HTML <datalist> element is and how it works.

What is <datalist> Tag in HTML?

Filling values in textboxes in HTML forms can sometimes be tedious! It is much easier if each textbox in a form had a prewritten list of values and we could just simply pick the related value from that list!

Or even there are times that we have a textbox somewhere in a document and we want users to put a value limited to a specific range! So now the question is, how can we declare this range of values to users to see?

In HTML they thought about this and hence came up with HTML <datalist> element!

HTML <datalist> element takes a list of values. After that, we can connect this list to an input box. Now if a user clicked that box, the list of values will automatically appear under that input box and the user can select the related value from this list instead of just typing it in!

HTML <datalist> Tag Syntax:

<datalist id= "datalist-id">

<option value = "value"> </option>


HTML <datalist> Tag Values

First of all, we need to set the id attribute of HTML <datalist> element. This is because for the target input element to link to the target <datalist>, it has an attribute named `list` and the value of this attribute is the value of `id` attribute we set for an HTML <datalist> element.

Now within the body of <datalist> element, we use HTML <option> to add values to this list. Basically, each <option> element represents one item on the list.

HTML <option> element has an attribute named `value` and in case of <datalist> element, we only need to fill the value of `value` attribute. We could also put a value in the body of <option> element as well, but for <datalist> that’s unnecessary!

Example: using <datalist> tag in HTML

See the Pen using <datalist> tag in HTML by Omid Dehghan (@odchan1) on CodePen.

Here the id of the <datalist> element is “brands”. So in the input box that we want to link this <datalist> element to, we’ve used the `list` attribute and set its value to `brands`. Now, in the output of this example, if we select the input box, the list of values will appear automatically and we can pick one of the items on the list.

Leave a Reply