如何在文本输入字段中添加逗号来分隔每组三位数?

发布于 2024-11-19 05:24:22 字数 229 浏览 2 评论 0原文

我有一个表单的文本输入字段,用户需要在其中输入数字。我想在每三个数字后自动插入一个逗号。

例如,输入“20”将得到“20”。输入“100”将得到“100”。但如果他们要输入“1000”,则会在 1 和后面的 0 之间插入一个逗号(例如,1,000)。显然,如果数字达到 7 位(例如 1,000,000),这种行为将会继续。

有没有简单的方法可以做到这一点?我对这一切都有点新手,所以请像在和孩子说话一样回答:)

I have a text input field for a form where users are meant to enter a number. I would like to automatically insert a comma after every third digit.

For example, entering '20' would result in '20'. Entering '100' would result in '100'. But if they were to enter '1000', a comma would be inserted between the 1 and the following 0's (e.g., 1,000). Obviously this behaviour would continue should the number reach 7 digits (e.g., 1,000,000).

Is there an easy way to do this? I'm a bit of a newb at all of this, so please answer like you're talking to a child :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

如歌彻婉言 2024-11-26 05:24:22

以下 javascript:

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

和以下 HTML:

<input type="text" onkeyup="format(this)">

应该可以解决您的问题。关键是使用“onkeyup”。

在这里尝试一下 http://jsfiddle.net/YUSph/

The following javascript:

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

and the following HTML:

<input type="text" onkeyup="format(this)">

should solve your problem. The key is to use 'onkeyup'.

Try it here http://jsfiddle.net/YUSph/

萌︼了一个春 2024-11-26 05:24:22

为了好玩:

'9876543210'
    .split('') // flip the entire string so that we can break every
    .reverse() //   3rd digit, starting from the end
    .join('')
    .split(/(...)/) // split on every 3rd
    .reverse()      // flip the string again, though now each group of 3 is
    .join(',')      //   backwards
    .replace(/,(?=,)|,$|^,/g, '') // remove extra ,
    .replace(/(,|^)(\d)(\d)?(\d)?/g, '$1$4$3$2') // flip each group of digits
// 9,876,543,210

有人想尝试让它变得更好吗?

for the fun of it:

'9876543210'
    .split('') // flip the entire string so that we can break every
    .reverse() //   3rd digit, starting from the end
    .join('')
    .split(/(...)/) // split on every 3rd
    .reverse()      // flip the string again, though now each group of 3 is
    .join(',')      //   backwards
    .replace(/,(?=,)|,$|^,/g, '') // remove extra ,
    .replace(/(,|^)(\d)(\d)?(\d)?/g, '$1$4$3$2') // flip each group of digits
// 9,876,543,210

Anyone want to take a stab at making that better?

心作怪 2024-11-26 05:24:22
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;
}

将输入的值传递给函数并使用返回的结果设置输入。您可以将其绑定到 onchange 事件。

下面是一个依赖 jquery 绑定更改事件并设置值的工作示例: http://jsfiddle.net/TYyfn /

逗号脚本来自:http://www.mredkj.com/javascript/nfbasic.html

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

Pass the value of the input into function and set the input with the result returned. You can bind this to an onchange event.

Here is a working example that relies on jquery to bind the change event and set the value: http://jsfiddle.net/TYyfn/

Comma script is from: http://www.mredkj.com/javascript/nfbasic.html

赤濁 2024-11-26 05:24:22

是的,这并不是非常困难。我相信参考可以满足您的需求。

请注意,要使其成为动态的(当它们键入时),您需要将其连接到输入字段更改处理程序。否则,您可以将其连接到输入字段模糊处理程序(这将具有在逗号离开字段时将逗号放入字段的效果)。

Yes, it's not terribly difficult. I believe this reference may give you what you need.

Note that for this to be dynamic (as they type) you'd need to have this wired to the input field change handler. Otherwise, you can wire this to the input field blur handler (which will have the effect of putting the commas in the field when they leave the field).

简单爱 2024-11-26 05:24:22

尝试一下:可能需要一些调整。

  1. 从上面获取函数: function addCommas(nStr){...} 并放入一个js文件中。

  2. 在页面标题中添加一个到 jquery 库的脚本链接:
    src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"

  3. 确保您的文本框具有唯一的 ID。例如:id="comma_input"。

  4. 在同一个js文件中添加

     $(文档).ready(function(){ 
         $('#comma_input').keyup(function(){
             $(this).attr('value',addCommas($(this).attr('value')));
         });
     });
    

Give this a try: it may need a little tweeking.

  1. take the function from above: function addCommas(nStr){...} and put in a js file.

  2. add a script link in the page header to jquery library with:
    src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"

  3. be sure your text box has a unique id. ex: id="comma_input".

  4. in the same js file add

     $(document).ready(function(){ 
         $('#comma_input').keyup(function(){
             $(this).attr('value',addCommas($(this).attr('value')));
         });
     });
    
不交电费瞎发啥光 2024-11-26 05:24:22
function addCommas(nStr){
    var offset = nStr.length % 3;
    if (offset == 0)
        return nStr.substring(0, offset) + nStr.substring(offset).replace(/([0-9]{3})(?=[0-9]+)/g, "$1,");
    else
        return nStr.substring(0, offset) + nStr.substring(offset).replace(/([0-9]{3})/g, ",$1");
}


alert(addCommas("1234567"));
function addCommas(nStr){
    var offset = nStr.length % 3;
    if (offset == 0)
        return nStr.substring(0, offset) + nStr.substring(offset).replace(/([0-9]{3})(?=[0-9]+)/g, "$1,");
    else
        return nStr.substring(0, offset) + nStr.substring(offset).replace(/([0-9]{3})/g, ",$1");
}


alert(addCommas("1234567"));
海拔太高太耀眼 2024-11-26 05:24:22

另一种方法,没有正则表达式,只是数组操作:

function decimalMark(s) {
    for (var a = s.split("").reverse(), b = [], i = 0; i < a.length; i++) { 
        if (i && i%3 === 0)
            b.unshift(",");
        b.unshift(a[i]);
    }

    return b.join("");
}

确保将字符串传递给函数

decimalMark("1234")

Another way to do it, no RegEx, just array manipulation:

function decimalMark(s) {
    for (var a = s.split("").reverse(), b = [], i = 0; i < a.length; i++) { 
        if (i && i%3 === 0)
            b.unshift(",");
        b.unshift(a[i]);
    }

    return b.join("");
}

Be sure to pass a string to the function

decimalMark("1234")
北渚 2024-11-26 05:24:22

纯JS中的简单字符串解决方案:

function addCommas(e) {
    var tgt = e.target, val = tgt.value.replace(/,/g, ''),
        amt = Math.ceil(val.length/3), newStr = '', x = 0; 
    while ( x <= amt ) {
        newStr += val.slice(x*3,(x+1)*3);
        newStr += ( x < amt-1 ) ? ',' : '';
        x++
    }
    tgt.value = newStr;
}
document.getElementById('test').addEventListener('change', addCommas, false);

演示:http://jsfiddle.net/ kevinvanlierde/TYyfn/141/

Simple string solution in pure JS:

function addCommas(e) {
    var tgt = e.target, val = tgt.value.replace(/,/g, ''),
        amt = Math.ceil(val.length/3), newStr = '', x = 0; 
    while ( x <= amt ) {
        newStr += val.slice(x*3,(x+1)*3);
        newStr += ( x < amt-1 ) ? ',' : '';
        x++
    }
    tgt.value = newStr;
}
document.getElementById('test').addEventListener('change', addCommas, false);

Demo: http://jsfiddle.net/kevinvanlierde/TYyfn/141/

如梦 2024-11-26 05:24:22

您可以使用标准 JavaScript 函数。示例在这里;
http://jsfiddle.net/azur/jD5pa/

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=UTF-8">
        <title>pure js solution</title>
        <script type='text/javascript'>
            function digitGroup(dInput) {
                var output = "";
                try {
                    dInput = dInput.replace(/[^0-9]/g, ""); // remove all chars including spaces, except digits.
                    var totalSize = dInput.length;
                    for (var i = totalSize - 1; i > -1; i--) {
                        output = dInput.charAt(i) + output;
                        var cnt = totalSize - i;
                        if (cnt % 3 === 0 && i !== 0) {
                            output = " " + output; // seperator is " "
                        }
                    }
                } catch (err)
                {
                    output = dInput; // it won't happen, but it's sweet to catch exceptions.
                }
                return output;
            }
        </script>
    </head>
    <body>
        <input type="text" value="53" onkeyup="this.value = digitGroup(this.value);">
    </body>
</html>

You can use standart JavaScript functions. Example here;
http://jsfiddle.net/azur/jD5pa/

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=UTF-8">
        <title>pure js solution</title>
        <script type='text/javascript'>
            function digitGroup(dInput) {
                var output = "";
                try {
                    dInput = dInput.replace(/[^0-9]/g, ""); // remove all chars including spaces, except digits.
                    var totalSize = dInput.length;
                    for (var i = totalSize - 1; i > -1; i--) {
                        output = dInput.charAt(i) + output;
                        var cnt = totalSize - i;
                        if (cnt % 3 === 0 && i !== 0) {
                            output = " " + output; // seperator is " "
                        }
                    }
                } catch (err)
                {
                    output = dInput; // it won't happen, but it's sweet to catch exceptions.
                }
                return output;
            }
        </script>
    </head>
    <body>
        <input type="text" value="53" onkeyup="this.value = digitGroup(this.value);">
    </body>
</html>
挖个坑埋了你 2024-11-26 05:24:22
var formatNumber = function(num, type) {
    var numSplit, int, dec, type;

    num = Math.abs(num);
    num = num.toFixed(2);

    numSplit = num.split('.')

    int = numSplit[0];
    if (int.length >= 3) {
        int = int.substr(0, int.length - 3) + ',' + int.substr(int.length - 3, 3);
    }

    dec = numSplit[1];

    return (type === 'exp'? sign = '-' : '+') + ' ' + int + '.' + dec;
};
var formatNumber = function(num, type) {
    var numSplit, int, dec, type;

    num = Math.abs(num);
    num = num.toFixed(2);

    numSplit = num.split('.')

    int = numSplit[0];
    if (int.length >= 3) {
        int = int.substr(0, int.length - 3) + ',' + int.substr(int.length - 3, 3);
    }

    dec = numSplit[1];

    return (type === 'exp'? sign = '-' : '+') + ' ' + int + '.' + dec;
};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文