Let’s review this HTML5 datalist tag, it is one of the new input, tags and form attributes in HTML5 forms.
This new element groups multiple predefined values that facilitates the autocompletion of an input type field. So that the user as he writes the browser opens a drop-down list with the different options to select.
The user is not forced to choose the value of the datalist, it simply suggests certain values.
This is the datalist syntax extracted from their official website:
<input list="colorlist"> <datalist id="colorlist"> <option value="Blue"> <option value="Red"> <option value="Yellow"> <option value="Black"> <option value="White"> </datalist>
In the syntax code we see that we first declare an input with the name of the list in the ‘list’ attribute. Then we write the new HTML5 datalist tag with the different values of the list and relate it to the input with the id ‘colorlist’.
That is, the attribute ‘list’ of the input and the ‘id’ of the datalist have to match, otherwise they will not be related and the list of suggested values will not be shown.
In this example of datalist tag we are going to suggest a series of colors as shown in the image below when we start typing ‘green’:
Here is the source code for the example demo:
<form name="form" id="form" action="/examples/2020/05-html5-datalist-tag.php" method="POST"> Write a color (Blue, red, yellow, black, green): <!-- The datalist with id 'lists' and the different values --> <datalist id="colorlist"> <option value="Blue"> <option value="Red"> <option value="Yellow"> <option value="Black"> <option value="Green"> </datalist> <!-- We associate to the input the datalist 'lists' --> <input name="color" list="colorlist"> <input type="submit" value="Send"> </form>
I explain you the code of the demo:
If we want to provide the <option> with some more information we can add the label attribute.
<datalist id="list"> <option value="blue" label="color blue"> <option value="red" label="color red"> <option value="yellow" label="color yellow"> <option value="black" label="color black"> <option value="green" label="color green"> </datalist>
The most common input types that support datalist in HTML5 are:
Finally we get by POST the selected value of the <datalist> from the value of the <input>:
<?php if($_POST) { echo "The selected color is: ".$_POST['color']; } ?>
I provide an example to obtain the value with jQuery. Here is the second example of HTML5 datalist:
<script type="text/javascript"> $(document).ready(function() { $("input[name=color]").change(function() { alert($("input[name=color]").val()); }); }); </script>
As you can see in the example, I get the value with the jQuery’s change() method.