I have multiple scripts handling the formatting of the inputs in a form (multi-part) form.
I have one script doing the math and converting the total to a fixed number sum (thanks to Irvin Dominin link description here and ElendilTheTall for this):
$(document).ready(function() {
$(function() {
$("body").on("blur", "#vehiclePrice, #estimatedTaxesAndFees, #downPayment, #manufacturerRebate, #tradeInValue, #amtOwedOnTrade, #extendedWarranty, #gapInsurance, #serviceContract", function() {
updateTotal();
});
var updateTotal = function() {
var input1 = parseInt($('#vehiclePrice').val()) || 0;
var input2 = parseInt($('#estimatedTaxesAndFees').val()) || 0;
var input3 = parseInt($('#downPayment').val()) || 0;
var input4 = parseInt($('#manufacturerRebate').val()) || 0;
var input5 = parseInt($('#tradeInValue').val()) || 0;
var input6 = parseInt($('#amtOwedOnTrade').val()) || 0;
var input7 = parseInt($('#extendedWarranty').val()) || 0;
var input8 = parseInt($('#gapInsurance').val()) || 0;
var input9 = parseInt($('#serviceContract').val()) || 0;
$('.total').text(input1 + input2 + input3 + input4 + input5 + input6 + input7 + input8 + input9);
$('.total').text('$'+sum.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,'));
var total = (input1 + input2 + input3 + input4 + input5 + input6 + input7 + input8 + input9);
};
});
});
I have two functions handling the input fields and adding a comma:
$(document).ready(function() {
$('input.number').keyup(function(event) {
// skip for arrow keys
if (event.which >= 37 && event.which <= 40) {
event.preventDefault();
}
var $this = $(this);
var num = $this.val().replace(/,/gi, "").split("").reverse().join("");
var num2 = RemoveRougeChar(num.replace(/(.{3})/g,"$1,").split("").reverse().join(""));
console.log(num2);
// the following line has been simplified. Revision history contains original.
$this.val(num2);
});
});
function RemoveRougeChar(convertString) {
if (convertString.substring(0,1) == ",") {
return convertString.substring(1, convertString.length)
}
return convertString;
};
Then yest another script preventing stripping out unwanted characters in the input fields:
function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
};
Ultimately what I am trying to do here is format the inputs with a comma, disallow any decimals, and then display a formatted value (only commas) in the div. All the while preventing any unwanted characters from being typed in the inputs.
If I try and use all the scripts together, it will only display the first numbers of the input fields, i.e. the ones before the commas.
Any ideas?