HTML 表单货币字段 - 自动将货币格式设置为 2 个小数和最大长度



美好的一天,

我在表格上有一个存款字段,该字段的货币自动格式化为包含 2 位小数(即用户键入 2500,该字段显示 25.00(。但是,我编写的脚本完全忽略了我在 html 中包含的最大长度。在这里看到我的小提琴。我已经尝试了各种jQuery选项来尝试强制执行限制,例如:

$('input[name=amount]').attr('maxlength',9);

这是我在页面上使用的脚本:

amountValue = "";
$(function() {
$(".mib").unbind().keydown(function(e) {
//handle backspace key
if (e.keyCode == 8 && amountValue.length > 0) {
amountValue = amountValue.slice(0, amountValue.length - 1); //remove last digit
$(this).val(formatNumber(amountValue));
} else {
var key = getKeyValue(e.keyCode);
if (key) {
amountValue += key; //add actual digit to the input string
$(this).val(formatNumber(amountValue)); //format input string and set the input box value to it
}
}
return false;
});
function getKeyValue(keyCode) {
if (keyCode > 57) { //also check for numpad keys
keyCode -= 48;
}
if (keyCode >= 48 && keyCode <= 57) {
return String.fromCharCode(keyCode);
}
}
function formatNumber(input) {
if (isNaN(parseFloat(input))) {
return "0.00"; //if the input is invalid just set the value to 0.00
}
var num = parseFloat(input);
return (num / 100).toFixed(2); //move the decimal up to places return a X.00 format
}
});

这是我的 HTML:

<input type="tel" id="amount" maxlength="10"  name="amount" class="full mib" pattern="d+(.d{2})?$" title="Please enter a valid number">

看起来您正在尝试进行金钱格式化。尝试这样的事情:

var convertStringToUSDFormat = function (value) {
// Create our number formatter.
var formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 2,
});
return formatter.format(value);
}

如果仍要使用脚本,请添加以下返回值:

if (key) {
amountValue += key; //add actual digit to the input string
if(amountValue.length >=10) return;
$(this).val(formatNumber(amountValue)); //format input string and set the input box value to it
}

最新更新