Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setter for HTMLInputElement.value

I'd like to subscribe for all changes of value property in all inputs using custom setter:

Object.defineProperty(HTMLInputElement.prototype, 'value', {
    set: function(newValue) {
       // do some logic here

       // WHAT PUT HERE to call "super setter"?
    }
});

If I use this.value = newValue; I'm getting Maximum call stack size exceeded which is quite right but...

Nevermind. What should I call to change value in correct way? Here is JSFIDDLE with more detailed explanation.

like image 903
Remek Ambroziak Avatar asked Mar 23 '26 15:03

Remek Ambroziak


1 Answers

Yes, this can be achieved using JavaScript:

(function (realHTMLInputElement) {
    Object.defineProperty(HTMLInputElement.prototype, 'value', {
        set: function (value) {
            // Do some logic here
            return realHTMLInputElement.set.call(this, value);
        },
    });
}(Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')));

We use a IIFE to pass in the original definition for value and then call the original set function from within our new definition.

If you combine that with a capture input event handler on document,¹ you get notified of all changes, whether via code (through the above) or by the user.

function yourCustomLogic(input, value) {
    console.log(`${input.id ? "Input #" + input.id : "An input"} set to "${value}"`);
}

// Catch programmatic changes
(function (realHTMLInputElement) {
    Object.defineProperty(HTMLInputElement.prototype, "value", {
        set: function (value) {
            // Do some logic here
            yourCustomLogic(this, value);
            return realHTMLInputElement.set.call(this, value);
        },
    });
})(Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value"));

// Catch end-user changes
document.addEventListener(
    "input",
    (event) => {
        if (event.target.tagName === "INPUT") {
            yourCustomLogic(event.target, event.target.value);
        }
    },
    true  // Capture handler
);

document.getElementById("example").value = "Updated by code.";
<input type="text" id="example">

The reason for using a capture phase handler (rather than bubbling phase) is twofold:

  1. Officially, input doesn't bubble, although most (all?) current browsers bubble it despite what the spec says

  2. It prevents event handlers that stop propagation from stopping the event before it gets to document

like image 119
bower Avatar answered Mar 26 '26 13:03

bower



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!