detect value change in input tag with vanilla javascript and MutationObserver

后端 未结 4 1066
一整个雨季
一整个雨季 2020-11-29 06:10

I want to detect when text/value change in input field. Even if I change the value with js, I want to detect that changes.

Here\'s what I\'ve tried so far in demo in

4条回答
  •  庸人自扰
    2020-11-29 06:43

    I've modified Shawn's method a little and wanted to share it. Can't believe there's actually a solution to this.

    Type into the input box to see the default behavior. Now, open the DevTools and select the input element, then change its value, e.g. $0.value = "hello". Examine the UI vs. API difference. It seems UI interactions do not modify value property directly. If it were, it would also log "...changed via API...".

    let inputBox = document.querySelector("#inputBox");
    
    inputBox.addEventListener("input", function () {
        console.log("Input value changed via UI. New value: '%s'", this.value);
    });
    
    observeElement(inputBox, "value", function (oldValue, newValue) {
        console.log("Input value changed via API. Value changed from '%s' to '%s'", oldValue, newValue);
    });
    
    function observeElement(element, property, callback, delay = 0) {
        let elementPrototype = Object.getPrototypeOf(element);
        if (elementPrototype.hasOwnProperty(property)) {
            let descriptor = Object.getOwnPropertyDescriptor(elementPrototype, property);
            Object.defineProperty(element, property, {
                get: function() {
                    return descriptor.get.apply(this, arguments);
                },
                set: function () {
                    let oldValue = this[property];
                    descriptor.set.apply(this, arguments);
                    let newValue = this[property];
                    if (typeof callback == "function") {
                        setTimeout(callback.bind(this, oldValue, newValue), delay);
                    }
                    return newValue;
                }
            });
        }
    }

提交回复
热议问题