Comma separating numbers

I have a text field where user can input currency amount.

When entering data , I want to add comma separating numbers into three digits without white spaces and if total digits are under three, then no comma added.

Example:
1234 => 1,234 and 123456789 => 123,456,789 and 123 => 123

You need to convert the number in to a string, and then add commas to that.

There are some plugins that can help you to perform this task, for example:


$.fn.digits = function(){ 
    return this.each(function(){ 
        $(this).text( $(this).text().replace(/(\\d)(?=(\\d\\d\\d)+(?!\\d))/g, "$1,") ); 
    })
};
// by using $('.numbers').digits()

Or as code that doesn’t require jQuery:


function digits (number) { 
    return number.toString().replace(/(\\d)(?=(\\d\\d\\d)+(?!\\d))/g, "$1,"); 
}
// by using digits(number)

How you are going to call that function ? onclick / on key down / on key up / jquery live ? how you are going to invoke that function?

Can you please post the html to check it out ?

That is entirely up to you, and comes down to what you are wanting to do in regards to the implementation of it.

I want the following implementation …here the user keeps on typing digits and value in the text field needs to updated as follows …

user type 1 ----> no comma

user type 2 — > value becomes 12 ----> no comma

user type 3 ----> value becomes 123 ---- >no comma

user type 4 ----> value becomes 1,234

user type 5 ----> value becomes 12,345

user type 6 ----> value becomes 123,456

user type 7 ----> value becomes 1,234,567

user type 8 ----> value becomes 12,345,678

user type 9 ----> value becomes 123,456,789

Is it possible to use your function to update text field data as above ? How do I invoke your function ?

Yes it is.

An example of how to invoke is shown at the end of the code.

For example, with digits(number)

No …I meant under what event you 'll call your function for that kind of output…

onclick / on key down / on key up / jquery live ?

or what else you use here ?

Yes, you could use any of those events to update the field.

is not “$1,” a Jquery variable here ? Do I need to import Jquery for this ? Am I missing something here ?

$1 is not a jQuery variable, it is a regular expression term that gets replaced with the first captured group.

Regular Expression documentation - where it says:

The following script uses the replace() method to switch the words in the string. For the replacement text, the script uses the $1 and $2 in the replacement to denote the first and second parenthesized substring matches.