简体   繁体   English

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

[英]How do I get the change event for a datalist?

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.编辑:这个问题与建议的问题不同,因为它是一个完全不同的问题。

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小提琴

Optimized Solution优化方案

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

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>

In browser with the inputType property on the InputEvent you can use that to filter out any unwanted onInput events.在 InputEvent 上具有inputType属性的浏览器中,您可以使用它来过滤掉任何不需要的 onInput 事件。 This is "insertReplacementText" on Firefox 81 and null for Chrome/Edge 86. If you need to support IE11 you will need to validate the value is valid.这是 Firefox 81 上的“insertReplacementText”,Chrome/Edge 86 上为 null。如果您需要支持 IE11,则需要验证该值是否有效。

 document.getElementById("browser") .addEventListener("input", function(event){ if(event.inputType == "insertReplacementText" || event.inputType == null) { document.getElementById("output").textContent = event.target.value; event.target.value = ""; } })
 <label for="browser">Choose your browser from the list:</label> <input list="browsers" name="browser" id="browser"> <datalist id="browsers"> <option value="Edge"> <option value="Firefox"> <option value="Chrome"> <option value="Opera"> <option value="Safari"> </datalist> <div id="output"> </div>

More Optimize更多优化

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

This might only be Chrome, untested anywhere else!这可能只是 Chrome,在其他任何地方都未经测试! , but I see a change event triggered when an option is selected. ,但我看到在选择选项时触发了change事件。 Normally change only happens in textfields when the field loses focus.通常,只有在文本字段失去焦点时才会在文本字段中发生change The change event triggers before the blur event IF it's a normal non-datalist change, so we have to check both: we're looking for a change that's not immediately followed by a blur :如果它是正常的非数据列表更改,则change事件在blur事件之前触发,因此我们必须检查两者:我们正在寻找未立即跟随blurchange

var timer;
el.addEventListener('change', function(e) {
    timer = setTimeout(function() {
        el.dispatchEvent(new CustomEvent('datalistchange'));
    }, 1);
});
el.addEventListener('blur', function(e) {
    clearTimeout(timer);
});

And then you can listen for the custom datalistchange event like normally.然后你可以像往常一样监听自定义datalistchange事件。 Or you can just put your specific logic instead of the dispatchEvent .或者您可以只放置您的特定逻辑而不是dispatchEvent

jsFiddle here jsFiddle在这里

The solutions above all have a big problem.以上所有解决方案都有一个大问题。 If the datalist has the option of (for example) "bob" and "bobby", as soon as someone types "bob", they code immediately says it's the same as clicking "bob"... but what if they were attempting to type "bobby"?如果数据列表有(例如)“bob”和“bobby”的选项,只要有人输入“bob”,他们的代码就会立即说这与单击“bob”是一样的......但是如果他们试图输入“鲍比”?

For a better solution, we need some more information.为了更好的解决方案,我们需要更多信息。 When listening for the 'input' event on the input field:在输入字段上侦听 'input' 事件时:

In Chromium-based browsers, when you type, delete, backspace, cut, paste, etc. in an input field, the event that is passed to the handler is an InputEvent , whereas when you select an option from the datalist, the event is just an Event type with a property of type that equals 'input'.在基于 Chromium 的浏览器中,当您在输入字段中键入、删除、退格、剪切、粘贴等时,传递给处理程序的事件是InputEvent ,而当您从数据列表中选择一个选项时,该事件是只是一个Event类型与属性type ,等于“输入”。 (This is also true during an auto-fill, at least with BitWarden). (在自动填充期间也是如此,至少对于 BitWarden)。

So you can listen for an 'input' event and check to see if it's an instance of InputEvent to determine if it's from autofill (which I think should be allowed since most of the time autofill won't be filling these types of fields, and if they do, it's usually a legit choice) / datalist selection.因此,您可以侦听“输入”事件并检查它是否是InputEvent的实例,以确定它是否来自自动填充(我认为应该允许,因为大多数时候自动填充不会填充这些类型的字段,并且如果他们这样做,这通常是一个合法的选择)/数据列表选择。

In Firefox, it's different, though.但在 Firefox 中,情况有所不同。 It still provides an InputEvent , but it has an inputType property with the value of "insertReplacementText", which we can also use.它仍然提供一个InputEvent ,但它有一个值为“insertReplacementText”的inputType属性,我们也可以使用它。 Autofill does the same thing as Chromium browsers.自动填充与 Chromium 浏览器的功能相同。

So here's a better solution:所以这里有一个更好的解决方案:

$('#yourInput').on('input', function(){
    if (
        !(e instanceof InputEvent) ||
        e.inputType === 'insertReplacementText')
    ) {
        // determine if the value is in the datalist. If so, someone selected a value in the list!
    }
});

I wish the browsers had the same implementation that had an event type/property that was exclusive to datalist selection, but they don't so this is the best I've got.我希望浏览器具有相同的实现,该实现具有数据列表选择独有的事件类型/属性,但它们没有,所以这是我所拥有的最好的。 I haven't tested this on Safari (I don't have access or time right now) so you should probably take a look at it and see if it's the same or has other distinguishing differences.我还没有在 Safari 上测试过这个(我现在没有访问权限或时间),所以你应该看看它,看看它是否相同或有其他区别。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM