开发者

Add comma to textbox every three digits using jQuery

I want to add comma to numbers every three digits on Textboxes.

I'm using t开发者_开发问答his 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();
        });

    });


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/


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


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


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


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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜