A DropDown menu in HTML 5 is accomplished using a combination of the new DataList element and the list attribute. This is done in two steps:
Step 1: Create a datalist and populate it with option elements as shown below:
<option value=Heroes>
<option value=LOST>
<option value=Fringe>
<option value=CriminalMinds>
<option value=CSIMiami>
</datalist>
Observe the ID attribute which is important to link this datalist with other elements on the page.
Step 2: Create an input element and link it to the datalist by setting the list attribute to the id of the associated datalist
When you run this example in a browser that support the HTML 5 datalist element and set focus on the TextBox, you will see a dropdown menu as follows:
The datalist element, as of this writing is supported only in FireFox 4+ and Opera 11.
In browsers like IE9, Chrome, Safari etc. that currently have not implemented support for the datalist element, you will see a regular text box. However this is not very consistent. What we would like is that in browsers that do not support DataList, atleast a standard dropdown control (SELECT element) should appear, which will allow users to select a value.
Note: Unlike the select element, users can enter data of their choice in datalist. It’s just that they’ll be presented with a set of suggested options in a drop-down as they type. That’s what makes the datalist control exciting to add to your forms.
Here’s how we can provide support for browsers not supporting the DataList by doing some minor changes in the code written previously
As you can observe, we have enclosed a ‘select’ element inside the datalist. All browsers supporting the datalist element will ignore the select element and display only the HTML5 datalist element.
However all older browsers or ones without the datalist support will display a dropdown. Cool ain’t it!
Additionally, we have also added text for each of the option elements
This is done because the select element in old browsers does not display the value attribute, but instead displays the text specified.
That’s it. Run the page and see the output
Remember that the Select list will only be shown in browsers that do not currently support the datalist element like IE, Chrome, Safari.
Tweet
4 comments:
awesome, but it is w3c compatible, thanks
Ugliest code I've seen in a long time. Anyone that uses your example is polluting the internet with invalid and sloppy code. Keep googling, folks. Nothing to see here.
thanks for your comment but then you need to also say what was ugly, invaid and sloppy about the code. The code shows one of the ways you provide a fallback option and its as simple as that!
Here is an alternative way to provide compatibility as a "Suggestion":
http://www.veniaminilmer.com/html/datalist-compatibility
Post a Comment