javascript 如何获取数据列表的更改事件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23647359/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 01:18:20  来源:igfitidea点击:

How do I get the change event for a datalist?

javascriptjqueryhtmlhtml-datalist

提问by user_78361084

I am using a datalist and need to detect when the user selects something from the drop-down list. A similar question has been askedBUT 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.

编辑:这个问题与建议的问题不同,因为它是一个完全不同的问题。

采纳答案by deadulya

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

您可以在更改时手动检查它。但是你需要检查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

小提琴

回答by Matee Gojra

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

回答by Abo Baker

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

请寻找您的解决方案,很好。有找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>

回答by roy.d

More Optimize

更多优化

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