Search code examples
javascriptfrontend

get set descriptors for input.value error


var inp = document.querySelector('input');
Object.defineProperty(inp, "value", {
    get: function() {
      console.log('getter');
      return this.value;
    },
    set: function(value) {
       console.log('setter');
       this.value = value + '1';
    }
});

I want to write my logic with set input value, but this code not working, infinity loop, when i try get or set value;

How i can do custom handler, on change value? (I need change value, in this way: input.value="custom", no input.setValue("custom")! )


Solution

  • You could do it like this:

    var inp = document.querySelector('input');
    
    function createGetSetValue( inputElement ){
      var value = inputElement.value;
      Object.defineProperty( inputElement, "value", {
        get: function(){ return value; },
        set: function( v ){ value = v + '1'; }
      });
      return inputElement;
    };
    
    createGetSetValue( inp );
    
    inp.value = 10;
    console.log( inp.value ) // Logs 101
    <input value="2" />

    Because when you use this.value = x, you are calling the setter again (causing the infinite loop). This will store the value independently and set up the getter and setter to return that value instead of the one actually stored in the input, allowing you to modify it without invoking the getter and setter again.