将逗号添加为千位分隔符(javascript)-输出将被删除 [英] Adding comma as thousands separator (javascript) - output being deleted instead

查看:66
本文介绍了将逗号添加为千位分隔符(javascript)-输出将被删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试动态调整输入的数值以包含千位分隔符

I am attempting to dynamically adjust a numerical value entered to include thousand separators

这是我的代码:

function addCommas(nStr) {
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}


<input type="number"  onkeyup="this.value=addCommas(this.value);" />

但是,当我在4个数字之后输入数字时,该字段将被清除.

However when I enter numbers after the 4 one, the field is cleared.

有什么想法我要去哪里吗?如果有jQuery解决方案,我已经在我的网站上使用它了.

Any ideas where I am going wrong? If there is a jQuery solution I'm already using that on my site.

推荐答案

尝试

<input type="text" onkeyup="this.value=addCommas(this.value);" />

相反.由于该功能只处理文本而不是数字.

instead. Since the function is working with text not numbers.

这篇关于将逗号添加为千位分隔符(javascript)-输出将被删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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