7

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();
        });

    });
Shahin
  • 12,543
  • 39
  • 127
  • 205

5 Answers5

7

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/

troynt
  • 1,900
  • 15
  • 21
1

You may want to use a so called "masked textfield", take a look at this jQuery Plugin

Tim Büthe
  • 62,884
  • 17
  • 92
  • 129
1

Try something along these lines...

Demo: http://jsfiddle.net/wdm954/8HDem/

(function( $ ) {
    $.fn.digits = function () {
        return this.each(function () {

            $(this).keydown(function() {
                var str = $(this).val(), cc = 0;
                for (var i=0; i<str.length; i++) if (str[i] == ',') cc++;
                if (str.length != 0 && (str.length - cc) % 3 == 0) {
                    $(this).val($(this).val() + ',');
                }
            });

        });
    };
})( jQuery );
wdm
  • 7,121
  • 1
  • 27
  • 29
0

Solution below takes care of cursor position jumping to the end of number when being edited in the middle, plus takes care of comma deletion and backspacing problem where with backspace or delete removed comma simply gets added back

 <script type="text/javascript">
    $(function () {
        $("[type='tel']").keydown(function (event) {
            var position = this.selectionStart;
            var $this = $(this);
            var val = $this.val();
            if (position == this.selectionEnd &&
                ((event.keyCode == 8 && val.charAt(position - 1) == "," && val.substr(0, position - 1).indexOf(".") == -1)
                || (event.keyCode == 46 && val.charAt(position) == "," && val.substr(0, position).indexOf(".") == -1))) {
                event.preventDefault();
                if (event.keyCode == 8) {
                    $this.val(val.substr(0, position - 2) + val.substr(position));
                    position = position - 2;
                } else {
                    $this.val(val.substr(0, position) + val.substr(position + 2));
                }
                $this.trigger('keyup', { position: position });
            } else {
                this.dispatchEvent(event);
            }
        });

                $("[type='tel']").keyup(function(event, args) {
                        if (event.which >= 37 && event.which <= 40) {
                                event.preventDefault();
                        }

                        var position = args ? args.position : this.selectionStart;
                        var $this = $(this);
                        var val = $this.val();
                        var parts =val.split(".");
                    var valOverDecimalPart = parts[0];
                        var commaCountBefore = valOverDecimalPart.match(/,/g) ? valOverDecimalPart.match(/,/g).length : 0;
                        var num = valOverDecimalPart.replace(/[^0-9]/g, '');
                        var result = parts.length == 1 ? num.replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,") : num.replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,") +"."+ parts[1].replace(/[^0-9.]/g,"");
                    $this.val(result);
                    var commaCountAfter = $this.val().match(/,/g) ? $this.val().match(/,/g).length : 0;
                        position = position + (commaCountAfter - commaCountBefore);
                        this.setSelectionRange(position, position);
                });
            });
    </script>
Matas Vaitkevicius
  • 58,075
  • 31
  • 238
  • 265
  • Hi Matas, I'm a bit confused by your behaviour here. You seem to have posted this answer (in various forms) 4 times on Stack Overflow... including on 2 questions which are about Java, and completely unrelated to jQuery. Note that posting duplicate answers is frowned upon. You should instead be voting-to-close questions as duplicates, or tailoring your answers to the question itself. Obviously, you should also not be posting irrelevant answers to questions either... http://stackoverflow.com/a/32071578, http://stackoverflow.com/a/32071539, http://stackoverflow.com/a/32071380, and here. – Matt Aug 18 '15 at 21:55
  • @Matt Hi Matt. Just trying to be useful really. It took me around one hour of looking for such mechanism, and when I was unable to find it I had to build it myself which took another 4. Now to save some time to others, I have posted it in places where I was looking for it myself (places it is most likely to be found, since half of people looking how to format with commas will have to do it for edit field and then they will need mechanism above). I do understand that they do not answer the original question. If you believe I should delete these helpful additions then please say so. Thanks. – Matas Vaitkevicius Aug 19 '15 at 08:13
0

How about using the jQuery Format plugin?

http://jsbin.com/uhima5/edit

<input type="text" id="n" value=""/> <a href="#" id="fmt">format</a>

and

$("#fmt").bind("click", function() {

    var nr = $("#n").val();
    var n = $.format.number(parseFloat(nr), '#,##0.00#');

    $("#n").val(n);
});
balexandre
  • 73,608
  • 45
  • 233
  • 342
  • This is to format, you did not specified in your question that you wanted to be formated as you type. If that's the case, you need to go with the Masked Input Plugin http://www.conetrees.com/2009/03/blog/jquery-masked-input-plugin-increase-usability-for-masked-format-input-fields/ – balexandre May 25 '11 at 08:14