The <datalist> tag is used to provide an in
autocomplete feature in the HTML files. It contains a list of predefined options that the user can select from, making it easier to enter data. The <datalist> tag is often used in conjunction with an <input> element of type “text” or “search”.
HTML
<!DOCTYPE html>
<html>
<body>
<form action="">
<label>Your Cars Name: </label>
<input list="cars">
<datalist id="cars">
<option value="BMW" />
<option value="Bentley" />
<option value="Mercedes" />
<option value="Audi" />
<option value="Volkswagen" />
</datalist>
</form>
</body>
</html>
Syntax
<input list="datalist-id" name="input-name" id="input-id" placeholder="Enter value...">
<datalist id="datalist-id">
<option value="Option 1">
<option value="Option 2">
<option value="Option 3">
...
</datalist>
Features of <datalist> Tag
- Autocomplete: When a user starts typing in the associated <input> field, the browser suggests matching options from the <datalist>.
- User Input: Users can either select from the list of options or enter a custom value that is not in the list.
- Cross-browser Support: Most modern browsers support the <datalist> element, but it’s always good to check for compatibility if you’re targeting older browsers.
More Example
HTML
<!DOCTYPE html>
<html>
<body>
<form action="">
<label>Your Cars Name: </label>
<input list="cars" id="carsInput" />
<datalist id="cars">
<option value="BMW" />
<option value="Bentley" />
<option value="Mercedes" />
<option value="Audi" />
<option value="Volkswagen" />
</datalist>
<button onclick="datalistcall()" type="button">
Click Here
</button>
</form>
<p id="output"></p>
<script type="text/javascript">
function datalistcall() {
var o1 = document.getElementById("carsInput").value;
document.getElementById("output").innerHTML =
"You select " + o1 + " option";
}
</script>
</body>
</html>
HTML <datalist> Tag – FAQs
What elements can be used inside the <datalist> tag?
The <datalist> tag contains <option> elements, each representing a predefined value users can select from or type.
Can users type values not listed in the <datalist> tag?
Yes, users can type values not listed in the <datalist> unless additional validation is implemented. The list simply suggests possible options.
Can the <datalist> tag be used for multiple input fields?
Yes, you can associate the same <datalist> with multiple <input> elements by referencing its id using the list attribute in each input.
How does the <datalist> tag differ from the <select> tag?
The <select> tag only allows selecting predefined options, while the <datalist> tag allows both selecting from suggestions and typing custom input.
Can you style the options inside a <datalist>?
Styling options within a <datalist> is limited, as browser default styling often overrides custom styles for the drop-down list.