Add Comma per 3 chars

by wdm954

HTML

<input id="test" type="text" />

CSS

input {
    width: 50%;
    padding: 3px;
}

JavaScript

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

$('#test').digits();