Search code examples
javascriptweb-componentcustom-element

Trying to define a getter on custom HTMLInputElement


I'm trying to change what is returned when you access the value property on this custom element - which extends HTMLInputElement. This would be used for entering currency values. The input would show 1,000.00 (string) but would return 1000 (float) through its value property.

Unfortunately, the getter doesn't seem to be executing.

function moneyStringToFloat(value) {
    value = value.replace(/[^0-9]/g, '');
    value = value / 100;

    return value;
}

class CustomInput extends HTMLInputElement {
    constructor() {
        super();
        this.type = "text";
    }
    
    static get value() {
        return moneyStringToFloat(this.value);
    }
}

customElements.define("custom-input", CustomInput, {extends: "input"});

const customInput = document.querySelector('input#customInput');
const output = document.querySelector('#output');

output.textContent = customInput.value;
<input is="custom-input"
  id="customInput"
  value="1,000.00">

<span id="output"></span>


Solution

  • You are defining a static getter. So, It was not worked. Static getters are accessed through the class itself, not through its instances.

    Here is updated version of your question.

    function moneyStringToFloat(value) {
        value = value.replace(/[^0-9]/g, '');
        value = value / 100;
    
        return value;
    }
    
    class CustomInput extends HTMLInputElement {
        constructor() {
            super();
            this.type = "text";
        }
        
        get value() {
            return moneyStringToFloat(super.value);
        }
    }
    
    customElements.define("custom-input", CustomInput, {extends: "input"});
    
    const customInput = document.querySelector('input#customInput');
    const output = document.querySelector('#output');
    
    output.textContent = customInput.value;

    Hope this will help you.