javascript 输入时格式化数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19113215/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 14:24:20  来源:igfitidea点击:

Format numbers on input

javascripthtml

提问by Ruddy

I have been looking around and can't seem to find an way to do this. As a user inputs a number into a input field e.g:

我一直在环顾四周,似乎无法找到一种方法来做到这一点。当用户在输入字段中输入一个数字时,例如:

<input type="text" class="numberOnly" id="miles" value="" />

How can I get that to update as they are typing to something like. e.g:

我怎样才能在他们输入类似的东西时更新它。例如:

Input: 100000

输入:100000

Output: 100,000

产量:100,000

I have some similar code that formats some other things as I calculate them, here is the function I'm using to format my other numbers.

我有一些类似的代码在我计算它们时格式化其他一些东西,这是我用来格式化其他数字的函数。

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

This works fine, like I said I'm not sure how to put the users input value into this and get the output back into the input field while they are typing.

这很好用,就像我说的那样,我不确定如何将用户输入值放入其中,并在他们打字时将输出返回到输入字段中。

Note: I need to format more then 1 input field.

注意:我需要格式化超过 1 个输入字段。

Update:

更新:

I have this in my code that will trigger each time the keyboard is pressed, so that can be used. This is used for the whole form so the form updates each time a button is pressed.

我的代码中有这个,每次按下键盘时都会触发,以便可以使用。这用于整个表单,因此每次按下按钮时表单都会更新。

 $(".numberOnly").keypress(function (e) {
            //if the letter is not digit then display error and don't type anything
            if (e.which != 8 && e.which != 46 && e.which != 0 && (e.which < 48 || e.which > 57)) {
                //display error message
                $("#errmsg").html("Digits Only").show().fadeOut(1600);
                return false;
            } else {
                $('input').keyup(function () {



                });
            }
        });

Update 2:

更新 2:

Is it possible to make an kind of overlay for it, e.g: the value of the input is 1000 but the overlay shows it to the use as 1,000?

是否可以为它制作一种叠加层,例如:输入的值为 1000,但叠加层将其显示为 1,000?

Any help would be great guys. Many thanks!

任何帮助都会是很棒的人。非常感谢!

采纳答案by 999k

Try with onkeypress event. Check this

尝试使用 onkeypress 事件。检查这个

<input type="text" class="numberOnly" id="miles" value="" onkeypress="format_num(id)" />
<SCRIPT LANGUAGE="JavaScript">
<!--
function format_num(id) {
var number = document.getElementById(id).value;
        number += '';
        number = number.replace(",","");
        x = number.split('.');
        x1 = x[0];
        x2 = x.length > 1 ? '.' + x[1] : '';
        var rgx = /(\d+)(\d{3})/;
        while (rgx.test(x1)) {
            x1 = x1.replace(rgx, '' + ',' + '');
        }
        document.getElementById(id).value = x1 + x2;
    }
//-->
</SCRIPT>

回答by Konstantin K

Good question. I had to deal with a similar problem in the past (in my case there were floating point numbers with two decimal points, so I had to keep track of the decimal point). Could not find any decent out of the box solution at the time. What I ended up doing was similar to your approach. However, instead of showing an error message you can edit the input value on the fly: detect unwanted characters and remove them from the string

好问题。过去我不得不处理类似的问题(在我的例子中,浮点数有两个小数点,所以我必须跟踪小数点)。当时找不到任何像样的开箱即用的解决方案。我最终做的与您的方法相似。但是,您可以即时编辑输入值,而不是显示错误消息:检测不需要的字符并将其从字符串中删除

$myInput.val(filterUnwantedCharacters($myInput.val()))

One problem here is that some browsers will reset the caret position to zero once you do this, so you may want to keep track of the caret position and set it after setting the input value. You may find this useful: http://www.examplet.org/jquery/caret.php

这里的一个问题是,一旦您这样做,某些浏览器会将插入符位置重置为零,因此您可能希望跟踪插入符位置并在设置输入值后进行设置。您可能会发现这很有用:http: //www.examplet.org/jquery/caret.php

Also, you may want to format your input on keydownrather than keypress, would feel more natural for the user.

此外,您可能希望将输入格式化为 ,keydown而不是keypress,这样用户会感觉更自然。

Not the easiest task, but with a bit of patience you can build a pretty decent formatter. Good luck!

这不是最简单的任务,但只要有一点耐心,您就可以构建一个相当不错的格式化程序。祝你好运!