Don of the Day

Don of the Day


Adventures in software development with Xamarin and the Web

Software developer, building things with code in sunny Scottsdale, AZ.

Share


Twitter


The HTML 5 datalist

Don FitzsimmonsDon Fitzsimmons

Recently, I had a need for a select list that could also act as a text box for input. Back in my ASP.Net WinForms days, we had such a component called the combobox. The combobox allowed a user to either select from a list of items in the drop down list, or to enter a new one in the text field.

With HTML, this is also possible using some clever CSS and JavaScript, but as I researched further, I came across a fairly new HTML element called the data list. Much like a typical select list, it's a list of option elements but the interesting part is, it can be associated to a text box. This presents the user with what appears to be a select list, but also functions as a text input:

<label>Choose a browser from this list:
<input list="browsers" name="myBrowser" /></label>
<datalist id="browsers">
  <option value="Chrome">
  <option value="Firefox">
  <option value="Internet Explorer">
  <option value="Opera">
  <option value="Safari">
</datalist>

The input is associated with the datalist by the "list" attribute and the datalist's id value. In the browser, the element looks like a select list but if you just click the text field area, it acts as text input. I think the original intention of this element is to provide filtering on a list, but it can also be used like the old combobox from WinForms, allowing the user to enter a value that doesn't exist in the list already.

I have found the behavior of the list to be a bit funky in Chrome. Sometimes, when clicking the down arrow to open the list, nothing will happen, but other than that occasional funkiness, this seems to work well and I plan to try and use it in my latest project.

Software developer, building things with code in sunny Scottsdale, AZ.

Comments