Sunday, September 15, 2024

Enabling Datalist Markup Element Options in HTML5

Introduction

Prior to HTML5, web developers had to use a lot of workarounds to provide users with a list of choices for an input element. The folks behind HTML5 realized this and ensure that first class support to input choice list was made part of the specification with the datalist element.

Simply put, the datalist markup element is used when user needs to be presented with a list of prefined options to enter into an input element. Datalist element isn’t rendered on the UI.

 

Syntax

Datalist markup element is specified with by providing an “id” for the list and a set of option values.

<datalist id=testlist>

<option value=”TestValue1″>

<option value=”TestValue2″>

</datalist>

 

We can see that the id for the datalist is “testlist” and it has 2 option values.

To use a datalist, on any input element, specify the list attribute and give it the id of the datalist from which to source values.

<input type=”text” id=”enterValue” list=”testlist”/>

 

Now when user interacts with enterValue element and starts typing, the web page will autosuggest completion if the inputted characters match any option values.

 

If no input is entered, and the user presses the down key, the input element will show a dropdown with all the possible values.

 

This helps the user enter the right values.

 

Sample listing

Let us look at an example of datalist.

<!DOCTYPE html>

<html>

<meta charset=”utf-8″>

<title>Datalist sample</title>

<body>

<label>

<input type=”text” id=”elementarygrade” list=”elementarygrades”/>

<datalist id=elementarygrades>

<option value=”K Kindergarten”>

<option value=”1 First”>

<option value=”2 Second”>

<option value=”3 Third”>

<option value=”4 Fourth”>

<option value=”5 Fifth”>

</datalist>

</label>

<button id=”buttonGo” type=”button”>Go</button>

 

<article>

<header>

<h1>Datalist sample</h1>

<p>Demo showing datalist in HTML5</p>

</header>

<footer>

<h1></h1>

<p>HTML Goodies</p>

</footer>

</article>

</body>

</html>

 

When the above HTML is rendered in a browser which understands datalist (not all browsers are HTML5 compliant), you can see the datalist in action.

 

 

 

Summary

In this article, we learned about how datalist markup element can be used to provide a list of options for an input element. I hope you have found this information useful.

 

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Popular Articles

Featured