键入时在数字上添加逗号 [英] Adding commas to numbers when typing

查看:37
本文介绍了键入时在数字上添加逗号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在用户键入数字时添加逗号.在Jquery中选择属性类型为 number input form-control 类的正确语法是什么?

I am trying to add commas when the user type a number. What is the correct syntax to select the input form-control class with attribute number type in Jquery?

我无法更改HTML代码,因为它是使用Bootstrap从Django输出的.

I can't change the HTML code since it is outputted from Django with Bootstrap.

HTML

<span class="input-group-addon">$</span>
<input class="form-control" id="id_step2-number_2"
       name="step2-number_2" type="number">
<span class="input-group-addon">.00</span>

JQuery

$(document).ready(function(){
    $("input[type='number']").keyup(function(event){
        // skip for arrow keys
        if(event.which >= 37 && event.which <= 40){
            event.preventDefault();
        }
        var $this = $(this);
        var num = $this.val().replace(/,/gi, "")
            .split("").reverse().join("");
          
        var num2 = RemoveRougeChar(
            num.replace(/(.{3})/g,"$1,").split("")
                .reverse().join("")
        );
          
        console.log(num2);

        // the following line has been simplified.
        // Revision history contains original.
        $this.val(num2);
    });
});
    
function RemoveRougeChar(convertString){
    if(convertString.substring(0,1) == ","){
        return convertString.substring(1, convertString.length)            
    }
    return convertString;
}

JSFiddle链接 https://jsfiddle.net/yWTLk/767/

推荐答案

首先,您不能使用 input type = number ,因为它不允许使用字符用于标记数字组.

First of all, you can't use input type=number, because it won't allow the character , which you are using to notate number group.

第二,使用良好的正则表达式,这实际上非常容易,并且不需要反向和反向,这很无聊.

Second, with a good regular expression, this is actually super easy, and really no need for reverse and reverse, which is boring.

var num = $this.val().replace(/,/gi, "");
var num2 = num.split(/(?=(?:\d{3})+$)/).join(",");

第一行从输入值中删除逗号.
第二行是魔术,它将值从最后到最后分成3组,然后用逗号连接.例如,'1234567'将成为 ['1','234','567'] .

The first line removes commas from input value.
The second line is magic, it splits the value into groups of 3 from last to first, then join with comma. For example, '1234567' will become ['1', '234', '567'].

我使用 split 只是为了展示RegExp的功能,实际上,我们不需要拆分和合并,只需直接替换即可:

I use split here is just to show the power of RegExp, in practice we don't need to split and join, just replace directly:

var num2 = num.replace(/\d(?=(?:\d{3})+$)/g, '$&,');

小提琴

但是,真正的魔力是,我敢打赌,你会大喊, toLocaleString !什么?!

But, the real magic is, I bet you would yell, toLocaleString! What?!

(1234567).toLocaleString() // "1,234,567"

这篇关于键入时在数字上添加逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆