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
The HTMLInputElement interface provides special properties and methods for manipulating the options, layout, and presentation of <input> elements.
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.
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);
})();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With