HTML <datalist> Tag โ Input Suggestions
๐ Introduction
The <datalist> tag is used to provide a list of predefined suggestions for an <input> field.
It helps users:
- Type faster
- Avoid errors
- Choose from recommended values
๐ It works together with <input> using the list attribute.
๐งฑ Syntax
<input list="options" />
<datalist id="options">
<option value="HTML"></option>
<option value="CSS"></option>
<option value="JavaScript"></option>
</datalist>
๐ก Example
<!DOCTYPE html>
<html>
<head>
<title>Datalist Example</title>
</head>
<body>
<h2>Choose a Programming Language</h2>
<form>
<label>Language:</label>
<input list="languages" />
<datalist id="languages">
<option value="HTML"></option>
<option value="CSS"></option>
<option value="JavaScript"></option>
<option value="Python"></option>
<option value="Java"></option>
</datalist>
<br /><br />
<button type="submit">Submit</button>
</form>
</body>
</html>
๐ฅ๏ธ Output Explanation
- User types inside the input field
- Suggestions appear automatically
- User can select or type manually
๐ฏ How It Works
๐ Two parts are required:
1. Input field
<input list="languages" />
2. Datalist with matching ID
<datalist id="languages"></datalist>
โ The list and id must match
๐ง Important Concept
๐ <datalist> is NOT a dropdown
| Feature | <select> |
<datalist> |
|---|---|---|
| User can type | โ No | โ Yes |
| Suggestions | โ Yes | โ Yes |
| Flexibility | Low | High |
๐งฉ Real Example
<input list="cities" placeholder="Enter city" />
<datalist id="cities">
<option value="Algiers"></option>
<option value="Oran"></option>
<option value="Constantine"></option>
</datalist>
๐ฏ When to Use <datalist>
Use it for:
- Search inputs
- City selection
- Email suggestions
- Search bars
- Auto-complete fields
๐ซ Common Mistakes
- Forgetting
listattribute โ - Mismatching
idโ - Using
<datalist>like<select>โ
๐จ Styling Example
<input list="cars" style="padding:5px;" />
<datalist id="cars">
<option value="BMW"></option>
<option value="Toyota"></option>
</datalist>
๐งช Mini Exercise
Create a form with:
- An input field for country
- A
<datalist>with at least 5 countries - A submit button
- Allow user to either type or select