
Originally Posted by
Raffles
The problem with commas is that you have to accept invalid numbers. For example, let's say I want to type "456,729.03" into the box. At some point, I will have typed "456,7" into the box, but that's an invalid number. So I think you will need a solution where commas are allowed at any position after a number, but then the contents are validated when the user has finished typing.
If you clarify what exactly you want to happen with the commas, then I can help you further.
Hello Raffles, Thank you for your reply. Basically if you typed 456 (I would not want you type a comma then 7. For the comma to be inserted, you would type 4567 and after the enter the 7, it turns into 4,567.
Another example:
if I type 1000 after that last 0 keystroke, it turns the value into 1,000. If I add 3 more zeros it turns it into 1,000,000. In the same vain if I subtract a 0 from the 1,000,000 the value is 100,000 instead.
I know there is a function that is called addCommas out there. But essentially, that works on a onclick event or onblur. I need to do it dynamically while typing, and I need it to work also if the user goes back to change the input value.
Code:
function addCommas(nStr)
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
Thanks for your assistance and hope it makes sense. I was trying to use this function in conjunction with the link I provided above in my original post but I am doing something wrong.
Bookmarks