javascriptcurrency-formatting

how to add currency pattern to input element while typing in javascript?


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

onChange and onblur Not works as typing

so i want while (as soon as ) i type it formats to me like

1000/000 or 100,000


Solution

  • function setFormat(id,separator) {
        let element = document.getElementById(id)
        let sepRegex = new RegExp(separator, 'g');
        let value = element.value.replace(sepRegex, ""); 
    
        if (!isNaN(value) && value != "") {
            var formattedValue = value.replace(/\B(?=(\d{3})+(?!\d))/g, separator);
            element.value= formattedValue; 
        }
    }
    #currency {
      text-align: left;
      direction: ltr;
    }
    <input type="text" id="currency" oninput="setFormat(this.id,'/')" >