How to get change event for datalist?

I am using a datalist and must determine when the user selects something from the drop-down list. A similar question was asked , but I need this to trigger the event ONLY when the user selects something from the datalist. If they inject something into the input, then I DO NOT want the event to fire. (Note that in the accepted answer to the question I linked, they link the input, which I don't want). I tried (without 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 from the proposed question because it is a completely different question.

+6
source share
4 answers

. .

$(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

+6

, , .

$(document).on('change', 'input', function(){
    var optionslist = $('datalist')[0].options;
    var value = $(this).val();
    for (var x=0;x<optionslist.length;x++){
       if (optionslist[x].value === value) {
          //Alert here value
          alert(value);
          break;
       }
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input list="data">
<datalist id="data">
    <option value='1'>Option 1 Here</option> 
    <option value='2'>Option 2 Here</option>
</datalist>
Hide result

/c1z0bnsm/7/

+3

Optimized Solution

$("input").on('input', function () {
    var inputValue = this.value;
    if($('datalist').find('option').filter(function(){
        return this.value == inputVal;        
    }).length) {
        //your code as per need
        alert(this.value);
    }
});
+2
source

Optimize more

$("input").on('input', function () {
if($('datalist').find('option[value="'+this.value+'"]')){
    //your code as per need
    alert(this.value);
}

});

0
source

Source: https://habr.com/ru/post/1540472/


All Articles