Formatting input value as user types

264 Views Asked by At

I am having difficulty updating an input fields value to currency while a user types. When I use the input event change I am able to successfully update the value to currency. But when I use keyup event the input value and interaction behavior is not very user friendly.

I tried using a setTimeout but I can't achieve the value/currency formatting as the user types correctly.

Any advice or suggestions would be greatly appreciated.

Example:

myInputElement.addEventListener('keyup', function (e) {
 e.currentTarget.value = numeral(e.currentTarget.value).format('$0,0.00');
});
2

There are 2 best solutions below

1
Ercan Peker On BEST ANSWER

make decimals optional.

numeral(e.currentTarget.value).format('$0,0.[00]');
1
S-- On

Try the "input" eventListener. This will fire every time a new character is input.

var myInputElement = document.getElementById("element");

myInputElement.addEventListener("input", function (e) {
  e.currentTarget.value = numeral(e.currentTarget.value).format('$0,0.00');
});