[英]HTML Form Currency Field - Auto Format Currency to 2 Decimal and Max Length
美好的一天,
我在具有自动格式化为包括2个小数的货币的表单上有一个存款字段(即用户键入2500,该字段显示25.00)。 但是,我编写的脚本完全忽略了我在html中包含的maxlength。 在这里看到我的小提琴 。 我已经尝试了各种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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.