如何在文本输入字段中添加逗号以分隔每组三位数字? [英] How can I add a comma to separate each group of three digits in a text input field?
问题描述
我有一个表单的文本输入字段,用户要输入一个数字。
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.
例如,输入'20'将得到'20'。输入100将导致100。但是如果他们输入1000,则在1和后面的0之间插入一个逗号(例如,1,000)。显然,如果数字达到7位数(例如,1,000,000),这种行为将继续。
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 :)
推荐答案
以下javascript:
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;
}
和以下HTML:
<input type="text" onkeyup="format(this)">
应该可以解决你的问题。关键是使用onkeyup。
should solve your problem. The key is to use 'onkeyup'.
在此尝试 http:// jsfiddle。 net / YUSph /
这篇关于如何在文本输入字段中添加逗号以分隔每组三位数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!