Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading