使用jQuery每隔三位数向文本框添加逗号

时间:2011-05-25 07:25:13

标签: jquery

我想在文本框上每三位数字添加逗号。
我正在使用此代码,但它不起作用。 我哪里错了?

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

    });

5 个答案:

答案 0 :(得分:7)

尝试以下方法:

// "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/

答案 1 :(得分:1)

您可能想要使用所谓的“屏蔽文本字段”,请查看此jQuery Plugin

答案 2 :(得分:1)

沿着这些方向尝试一些事情......

演示: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 );

答案 3 :(得分:0)

如何使用jQuery Format插件?

  

http://jsbin.com/uhima5/edit

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

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

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

    $("#n").val(n);
});

答案 4 :(得分:0)

下面的解决方案在中间编辑时将光标位置跳到数字末尾,加上逗号删除和退格问题,其中退格或删除删除的逗号只是被添加回来

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