How do I dynamically auto format a number to American Currency using jQuery only?

1.3k Views Asked by At

I am building a form, and I need to have an textbox where the user can enter prices or fees.

I have seen a form that can do what I am looking for, but I am not sure how to do it. What I am looking for, is by default, the textbox contains $0.00. As the user starts to type the number, it acts as follows: 12345678 starts as 0.01 > 0.12 > 1.23 > --- > $123,456.78

It needs to automatically add the commas where needed the and period for the cents only allowing 2 digits on the right side of the period.

It also need to BLOCK the ability to enter a non-numeric character other than the comma and period. So if the user were to type "a", instead of an "a" being displayed then suddenly removed, I don't even want to be able to see the "a".

1

There are 1 best solutions below

4
On

I would start by suggesting <input type="number"/> to restrict the input to numbers only. Next, here's the regex to handle two decimal places and commas.

var money = number.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,');

Where number is the number you would get on keyup. This should work when called on input.

$('input[type="number"]').on('keyup', function(e){
    var number = Number($(this).val());
    var money = number.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
    $(this).val(money);
});

This part is only the beginning. There's a few conditionals you'd need to put in. For example, you might want to check for the key that was pressed before allowing a change. You can do that by checking for keycodes.