The <datalist> tag is used to provide a list of elements to the user to select from this particular list. Text Box auto complete is the most popular widget after the popularity of AJAX framework. We can achieve the auto complete by using the html and javascript code. Every JS framework has the built-in functionality to support the auto complete for their input fields. In HTML5, it supports the similar function by using the <datalist> tag. With this tag, you can pass set of values and those values will be displayed for that input field. This tutorial highlights the benefits of using that tag with example.
This tag is completely different from the <select> tag. In the <select> tag, the user has to select the pre-defined values. There is no option for the manual user inputs. Where as in the <datalist>, the values are only the suggestions. If the user selects any of the value, it will be shown in the input field. Otherwise user can give his own input. That is the key difference between <select> and <datalist>.
The Syntax of <datalist>
<datalist id = “string”> Body content </datalist>
HTML5 <datalist> Example
<!DOCTYPE html> <html> <head> <title> Datalist element </title> </head> <body> <h3>Select your favourite Player</h3> <input list= "player"> <datalist id= "player"> <option value= "Virat Kohli"></option> <option value= "M S Dhoni"></option> <option value= "Sachin Tendulkar"></option> <option value= "Gautam Gambhir"></option> <option value= "Suresh Raina"></option> </datalist> </body> </html>
In the above code we are listing the player names using the <datalist> tag. Type some letter say “S” in the input tag and the list of player names containg letter “S” would be displayed below.
Example Application Test
- Save the file as datalist_example.html in your system.
- Just open the file in the browser, you will see the below picture in the browser. Note that the browser must support HTML5 specification.
Output
When the execution process is completed successfully we will get the following output :