How do I get the change event for a datalist?

五迷三道 提交于 2019-12-21 04:54:10

问题


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.


回答1:


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




回答2:


Please have look for your solution it's good to go. Have look for Demo

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

et/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);
    }
});



回答4:


More Optimize

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

});



来源:https://stackoverflow.com/questions/23647359/how-do-i-get-the-change-event-for-a-datalist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!