Web development and examples of PHP, jQuery, HTML5, WordPress, MySQL & AMP


HTML5 Datalist tag: Suggests a list of values in a form

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.

HTML5 Datalist tag Syntax

This is the datalist syntax extracted from their official website:

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.

Example of HTML5 datalist tag

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’:

HTML5 datalist tag

Here is the source code for the example demo:

I explain you the code of the demo:

  • We create a simple form with action POST.
  • We create a <datalist> tag id with an <option> set of tags to put the suggested colors.
  • We relate the <input> with the <datalist> using the ‘list’ attribute.

If we want to provide the <option> with some more information we can add the label attribute.

Supported Input Types

The most common input types that support datalist in HTML5 are:

  • text
  • url
  • tel input
  • color input
  • range input
  • datetime

Get the value of the HTML5 datalist with PHP

Finally we get by POST the selected value of the <datalist> from the value of the <input>:

Get the value of datalisttag with jQuery

I provide an example to obtain the value with jQuery. Here is the second example of HTML5 datalist:

As you can see in the example, I get the value with the jQuery’s change() method.

Cookie Policy

This website uses cookies to provide you with the best user experience. If you continue to browsing you are consenting to the acceptance of these cookies and acceptance of our cookie policy, click the link for more information.

ACEPTAR
Aviso de cookies