Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to overload the native HTMLInputElement value getter?

I am wondering if it is possible to modify a HTMLInputElement to display something different than the value prop returns.

Why that? Well sometimes you want to display the user something nice like a string, but you want to post an ID to the server. If you are using multiple logic/plugins on the input it starts getting problematic with using an additional fake one. So why not include both into one?! =)

I already noticed it is possible to define a getter for the value prop. But I loose the native setter functionality which will change the displayed text. =/

HTML:

<input id="foobar" type="text"/>

JS:

var input = document.getElementById('foobar');
    input.value = 'Mr. Foo Bar';
    input.myHiddenValue = 123;

Object.defineProperty(input, 'value', {
    get: function(){
        return this.myHiddenValue; 
    }
});

So if you can tell me, if this is possible and keep the native setter or just a silly late night idea, let me know xD

like image 366
Möhre Avatar asked Nov 09 '15 23:11

Möhre


People also ask

Why we use HTMLInputElement?

The HTMLInputElement interface provides special properties and methods for manipulating the options, layout, and presentation of <input> elements.

What is HTML input element?

The <input> tag specifies an input field where the user can enter data. The <input> element is the most important form element. The <input> element can be displayed in several ways, depending on the type attribute.


1 Answers

Although I don't recommend doing that, you can get (and cache) the native setter by using Object.getOwnPropertyDescriptor, e.g:

(function() {
  var descriptor = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value');

  descriptor.get = function() {
    // do whatever you want to do here
  }

  Object.defineProperty(HTMLInputElement.prototype, 'value', descriptor);  
})();
like image 52
Buzinas Avatar answered Oct 27 '22 02:10

Buzinas