How do I get the change event for a datalist?

user_78361084 picture user_78361084 · May 14, 2014 · Viewed 26.4k times · Source

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.

Answer

deadulya picture deadulya · May 14, 2014

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

$(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) {
          alert(val);
          break;
       }
    }
});

FIDDLE