HTML: How to make a combo box using datalist

A combo box is a combination text box and select menu, rolled into one. It uses a little known HTML5 element called “datalist”, which is supported by all of the modern browsers, but was never supported by Safari or late versions of Internet Explorer.

To set up an HTML5 combo box, start by creating a text input, and give this text input a list attribute that matches the id of the datalist. For example:

<input type="text" value="" list="colorlist" class="b"/>

Notice list=”colorlist”.

Then set up the datalist, in much the same way as you would set up a select menu. For example:

  <datalist id="colorlist">
      <option value="Black"></option>
      <option value="Blue"></option>
      <option value="Dark Green"></option>
      <option value="Grey"></option>
      <option value="Green"></option>
      <option value="Indigo"></option>
      <option value="Red"></option>
      <option value="Violet"></option>
      <option value="White"></option>
      <option value="Yellow"></option>
  </datalist>

Now if you place your cursor in the text field and hit the down arrow, you will see a select menu.

Also if you type a letter, a select menu will appear below, filtered to the letter typed.

Note: In Firebox, the menu will be filtered to any entries that include the letter, while Chrome will be filtered to any entries that start with the letter.

Here is the complete HTML:

  <input type="text" value="" list="colorlist" class="b"/>
  <datalist id="colorlist">
      <option value="Black"></option>
      <option value="Blue"></option>
      <option value="Dark Green"></option>
      <option value="Grey"></option>
      <option value="Green"></option>
      <option value="Indigo"></option>
      <option value="Red"></option>
      <option value="Violet"></option>
      <option value="White"></option>
      <option value="Yellow"></option>
  </datalist>

 

If you need to find a solution that will work with older browsers and Safari, here is some JavaScript that can be used:

var nativedatalist = !!('list' in document.createElement('input')) && 
    !!(document.createElement('datalist') && window.HTMLDataListElement);

if (!nativedatalist) {
  $('input[list]').each(function () {
    var availableTags = $('#' + $(this).attr("list")).find('option').map(function () {
      return this.value;
    }).get();
    $(this).autocomplete({ source: availableTags });
  });
}

Here is a complete working example on codepen:

See the Pen Combo Box (JavaScript) by Chris Nielsen (@Chris_Nielsen) on CodePen.0

 

For more information about HTML5 datalist, see:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/datalist