在使用 C# 的 asp.net-mvc 项目中。
感谢this post,我使用一个函数来用逗号格式化较大的数字,例如1,000,000
:
function numberWithCommas(str) {
return str.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
问题是,我将输入锁定为只接受最小值为零的数字。
<input type="number" min="0" class="myclass" value="@somevalue" />
这在使用 JS 时会出现问题,因为它只需要输入数字。这让我想到了这样的问题 How to make HTML input tag only accept numerical values? ,也提供了JS解决方案。
我想知道是否有人开发了一种优雅的方式来格式化数字输入显示,同时验证数字输入,这里还有其他可用的选项吗?它不一定是纯粹的 JS 解决方案。
最佳答案
您不能使用数字输入,因为 JavaScript 不会将格式化数字视为数字。
选项是使用非数字输入,但过滤掉任何“有问题的”字符。
在以下示例中,我还将处理点分隔符,以防您需要接受分数。
在编辑文本框时,它还必须保留光标位置。我在 Updating an input's value without losing cursor position 的帮助下实现了它。 .
function format(inp){
var start = inp.selectionStart, // get the selection start
end = inp.selectionEnd; // and end, as per the linked post
var s1=inp.value.split(",").length-1; //count the commas before edit
inp.value=numberWithCommas(inp.value.replace(/,|[^\d.]/g,''));
var s2=inp.value.split(",").length-s1-1; //count the commas after edit so as to know where to place the cursor, as the position changes, if there are new commas or some commas have been removed
inp.setSelectionRange(start+s2, end+s2); // set the selection start and end, as per the linked post
}
function numberWithCommas(str) {
var a=str.split('.');
var p=/\B(?=(\d{3})+(?!\d))/g;
if(a.length>1)
return a[0].toString().replace(p, ",")+"."+a[1];
else
return str.toString().replace(p, ",");
}
<input onkeyup="format(this)">
https://stackoverflow.com/questions/37640891/