Numbers Only Input converted to currency (Solution)
allow number only input and change input value to currency
by Ian Roberts
HTML
<input type="text" id="numbersonly" />
JavaScript
const currencyFormatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 0
});
const currencyUnformatter = function(string) {
//console.log(string.replace(/\$/g, "").replace(/\,/g, "").replace(/,/g, ""))
return string.replace(/\$/g, "").replace(/\,/g, "").replace(/,/g, "")
}
const keyNumbersArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
const arrowKeyValues = ["ArrowUp","ArrowRight","ArrowDown", "ArrowLeft"]
document.getElementById('numbersonly').addEventListener('keydown', function(e) {
let isKeyNumber = parseInt(e.key); // either 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 or NaN
let str = window.str = `${this.value}`
// keyArray.includes(key) returns true
if (keyNumbersArray.includes(isKeyNumber)) {
// we have a successful number key press
// because we are reading this.value on keydown and not on keyup, check if this is the first input
if (this.value.length === 0) {
//let inputValueFormattedCurrency = currencyFormatter.format(`${this.value}`)
this.value = `$${this.value}` // ex: if first input is 1, prints $1
//console.log(`${this.value}`)
} else {
// TODO: account for injecting ${isKeyNUmber} where cursor is at
e.preventDefault();
//console.log(`${this.value}${isKeyNumber}`)
let inputValueUnformattedCurrency = currencyUnformatter(`${this.value}`)
//console.log(`${inputValueUnformattedCurrency}${isKeyNumber}`)
// for testing
// this.value = inputValueUnformattedCurrency
//console.log(this.selectionStart)
//console.log(this.selectionEnd)
let inputValueFormattedCurrency = currencyFormatter.format(`${inputValueUnformattedCurrency}${isKeyNumber}`)
//console.log(`${inputValueFormattedCurrency}`)
this.value = `${inputValueFormattedCurrency}`
}
/* console.log(currencyUnformatter(this.value)) */
} else if (e.key === 'Backspace') {
// console.log(e.key)
// console.log('string length: ', this.value.length)
//...