Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add comma to textbox every three digits using jQuery

Tags:

jquery

I want to add comma to numbers every three digits on Textboxes.
I'm using this code but it not works. Where am I wrong?

  $(function () {
        $.fn.digits = function () {

            return this.each(function () {
                $(this).val($(this).val().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,"));
            })
        }
        $("#Test").bind("change keyup keydown paste blur", function (e) {

            $("#Test").digits();
        });

    });
like image 663
Shahin Avatar asked May 25 '11 07:05

Shahin


People also ask

How do you put a comma in input type numbers?

You can use type="text" and then add commas to the number in the onchange event.

How Split comma Separated Values in jquery?

Answer: Use the split() Method You can use the JavaScript split() method to split a string using a specific separator such as comma ( , ), space, etc.


1 Answers

Try the following:

// "1234567".commafy() returns "1,234,567"
String.prototype.commafy = function() {
  return this.replace(/(.)(?=(.{3})+$)/g,"$1,")
}
$.fn.digits = function () {
    return this.each(function () {
        $(this).val($(this).val().commafy());
    })
}

JSFiddle http://jsfiddle.net/BrUVq/1/

like image 83
troynt Avatar answered Nov 15 '22 10:11

troynt