如果需要,可以使用逗号和小数自动设置货币输入字段的格式。 文本会自动使用逗号进行格式化,并且光标会在格式化后放回到用户离开的位置,而光标会移动到输入的末尾。 验证在 KeyUp 上进行,最终验证在模糊上完成。
超文本标记语言
<input type="text" class="currency">
JavaScript
$(".currency").on({
keyup: function() {
let input_val = $(this).val();
input_val = numberToCurrency(input_val);
$(this).val(input_val);
},
blur: function() {
let input_val = $(this).val();
input_val = numberToCurrency(input_val, true, true);
$(this).val(input_val);
}
});
var numberToCurrency = function(input_val, fixed = false, blur = false) {
// don't validate empty input
if(!input_val) {
return "";
}
if(blur) {
if(input_val === "" || input_val == 0) { return 0; }
}
if(input_val.length == 1) {
return parseInt(input_val);
}
input_val = ''+input_val;
let negative = '';
if(input_val.substr(0, 1) == '-'){
negative = '-';
}
// check for decimal
if(input_val.indexOf(".") >= 0) {
// get position of first decimal
// this prevents multiple decimals from
// being entered
var decimal_pos = input_val.indexOf(".");
// split number by decimal point
var left_side = input_val.substring(0, decimal_pos);
var right_side = input_val.substring(decimal_pos);
// add commas to left side of number
left_side = left_side.replace(/\D/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",");
if(fixed && right_side.length > 3) {
right_side = parseFloat(0+right_side).toFixed(2);
right_side = right_side.substr(1, right_side.length);
}
// validate right side
right_side = right_side.replace(/\D/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",");
// Limit decimal to only 2 digits
if(right_side.length > 2) {
right_side = right_side.substring(0, 2);
}
if(blur && parseInt(right_side) == 0) {
right_side = '';
}
// join number by.
// input_val = left_side + "." + right_side;
if(blur && right_side.length < 1) {
input_val = left_side;
} else {
input_val = left_side + "." + right_side;
}
} else {
// no decimal entered
// add commas to number
// remove all non-digits
input_val = input_val.replace(/\D/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
if(input_val.length > 1 && input_val.substr(0, 1) == '0' && input_val.substr(0, 2) != '0.') {
input_val = input_val.substr(1, input_val.length);
} else if(input_val.substr(0, 2) == '0,') {
input_val = input_val.substr(2, input_val.length);
}
return negative+input_val;
};