Perform action when clicking HTML5 datalist option

Sorry for digging up this question, but I’ve had a similar problem and have a solution, that should work for you, too.

function onInput() {
    var val = document.getElementById("input").value;
    var opts = document.getElementById('dlist').childNodes;
    for (var i = 0; i < opts.length; i++) {
      if (opts[i].value === val) {
        // An item was selected from the list!
        // yourCallbackHere()
        alert(opts[i].value);
        break;
      }
    }
  }
<input type="text" oninput="onInput()" id='input' list="dlist" />

<datalist id='dlist'>
  <option value="Value1">Text1</option>
  <option value="Value2">Text2</option>
</datalist>

This solution is derived from Stephan Mullers solution. It should work with a dynamically populated datalist as well.

Unfortunaltely there is no way to tell whether the user clicked on an item from the datalist or selected it by pressing the tab-key or typed the whole string by hand.

Leave a Comment