How do I get the change event for a datalist?

前端 未结 6 697
轮回少年
轮回少年 2021-02-05 11:14

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 wh

6条回答
  •  广开言路
    2021-02-05 11:54

    This might only be Chrome, untested anywhere else!, but I see a change event triggered when an option is selected. Normally change only happens in textfields when the field loses focus. 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:

    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. Or you can just put your specific logic instead of the dispatchEvent.

    jsFiddle here

提交回复
热议问题