How do I get the change event for a datalist?

html, html-datalist, javascript, jquery

Solution

You can manually check it on change. But you need to check change of the input of datalist.

FIDDLE

$(document).on('change', 'input', function() {
  var options = $('datalist')[0].options;
  var val = $(this).val();
  for (var i = 0; i < options.length; i++) {
    if (options[i].value === val) {
      console.log(val);
      break;
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<input list="ff">
<datalist id="ff">
  <option>Option 1 Here</option>
  <option>Option 2 Here</option>
</datalist>

Problem

I am using a datalist and need to detect when the user selects something from the drop-down list. A similar question has been asked BUT I need it so that the event fires ONLY when the user selects something from the datalist. If they type something in the input then I do NOT want the event to fire. (Notice in the accepted answer to the question I linked that they bind the input, which is not what I want). I've tried (with no success): ``` <datalist> <option>Option 1 Here</option> <option>Option 2 Here</option> </datalist> $(document).on('change', 'datalist', function(){ alert('hi'); }); ``` EDIT: This question is different than the suggested question because it's a completely different question.

Original source

Related problems