Question

How do I get an input field (text) to accept only numbers and to automatically format it to two decimal places, as the user is typing in each digit?

For example, the default value of the field is 0.00 User wants to enter 23.50

Step 1: user types 2 - field shows 0.02
Step 2: user types 3 - field shows 0.23
Step 3: user types 5 - field shows 2.35
Step 4: user types 0 - field shows 23.50

Thanks in advance!

Was it helpful?

Solution

the following regex expression matches 99.99, 99999.99, etc.

\$\d+\.\d{2}

use jQuery's .live() function to wire the keyup event to your text box.

$('.textBoxDecimalOnly').live('keyup', function () {
    // inside this keyup hook, grab the value in the text box.
    // if it matches the regex... do something
    // else do something different
});

when keyup happens, check the value of the text box against that regex expression and do what you wish with your answer.

to make it work from right to left you could reformat the string...

// 1. get text in the box.
// 2. if length < 3 ... append a "." to the first string.
// 3. if > 3 get the index of the 2nd to last character and append "." just before it.

stuff that logic inside your live hook.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top