Formatera valutainmatningsfält automatiskt med kommatecken och decimaler om det behövs. Text formateras automatiskt med kommatecken och markören placeras tillbaka där användaren slutade efter formatering kontra att markören flyttade till slutet av inmatningen. Validering sker på KeyUp och en slutlig validering görs på oskärpa.
HTML
<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;
};