skip to Main Content

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>

2

Answers


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

    Login or Signup to reply.
  2. Since extends HTMLInputElement will never work in Safari, because Apple has, rightly so, argumented they will never implement Customized Built-In Elements.

    You can use an Autonomous Element:

    customElements.define("custom-input", class extends HTMLElement {
        connectedCallback() {
          this.innerHTML = `<input type="text" placeholder="Enter a monetary value"/>`;
        }
        get value() {
          let value = this.querySelector("input").value;
          return (value.replace(/[^0-9]/g, '')) / 100;
        }
    });
    $ <custom-input onchange="alert(this.value)"></custom-input>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search