HTML - <datalist> Tag



The HTML <datalist> element contains a set of <option> elements that represent acceptable or recommended options available to choose from among other controls.

The HTML <datalist> tag specifies a list of pre-defined options for the <input> element, it provides autocomplete features to an input element, when the user clicks on the input field they will show the dropdown list of pre-defined options. The id attribute of <datalist> tag is equal to the list attribute of an input field.

Syntax

Following is the syntax for HTML <datalist> tag −

<datalist>.......</datalist>

Example

Let's look into the following example, where we are going to use the datalist tag without input element.

<!DOCTYPE html>
<html lang="en">
<head>
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>HTML datalist tag</title>
</head>
<body>
   <form>
      <input list="values">
      <datalist id="values">
         <option value="HTML">
      </datalist>
   </form>
</body>
</html>

When we run the above code, it will generate an output displaying nothing on the webpage. because we are using the datalist tag without input element.

Example

Considering, the another scenario where we are going to use the datalist tag along with the input element.

<!DOCTYPE html>
<html lang="en">
<head>
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>HTML datalist tag</title>
</head>
<body>
   <!--create a datalist-->
   <p>Choose your option</p>
   <input type="text" list="values">
   <datalist id='values'>
      <option value="HTML">HTML</option>
      <option value="CSS">CSS</option>
      <option value="JavaScript">JavaScript</option>
   </datalist>
</body>
</html>

On running the above code, the output window will pop up displaying the dropdown list on the webpage.

Example

In the following example, we are going to use the datalist tag with the date and time type.

<!DOCTYPE html>
<html lang="en">
<head>
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>HTML datalist tag</title>
</head>
<body>
   <!--create a datalist-->
   <p>Choose your Time</p>
   <input type="time" list="hours">
   <datalist id='hours'>
      <option value="08:00"></option>
      <option value="10:00"></option>
      <option value="12:00"></option>
   </datalist>
</body>
</html>

When we run the above code, it will generate an output consisting of the predefined dropdown menu along with a text displayed on the webpage.

html_tags_reference.htm
Advertisements