0

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

Matt
  • 31
  • 8

1 Answers1

0

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.

Community
  • 1
  • 1
Donnie D'Amato
  • 3,832
  • 1
  • 15
  • 40
  • Okay... I guess I'm confused where to call the variable "money"? – Matt Nov 19 '15 at 02:52
  • That's just an example of the regex. I put the full function below that which uses the regex. – Donnie D'Amato Nov 19 '15 at 02:54
  • hmm... I tried adding exactly what you answered, then I changed the input[type="number"] to the actual ID I'm using, then I took out everything and just left a blank page with the textbox (type="number") and your answer, and nothing seems to be changing. Depending on the location of your answer, it either does nothing different, (won't allow letters due to type="number" but that's it) or as soon as I type a number, it immediately gets deleted – Matt Nov 19 '15 at 03:07
  • Ah, first problem is the input is sending into the function as text. Needs to be converted to a number first. – Donnie D'Amato Nov 19 '15 at 03:14