isaac weathers
isaac weathers

Reputation: 1472

Format input fields with commas and display in Div as numeric formatted values

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?

Das Fiddle

Upvotes: 0

Views: 2375

Answers (2)

Irvin Dominin
Irvin Dominin

Reputation: 30993

Currently there are three issues:

  1. the type="number" for you input elements allows, if the browser support it, you to enter only numbers, but you are appending , to your number so it natively clear the value, switch it into type="text"
  2. the sum is not performed in the right way because of the , try removing it using .replace(/,/gi,'') and then parse as number
  3. in the isNumberKey function you are using event instead of evt

Code:

$( 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().replace(/,/gi,'')) || 0;
    var input2 = parseInt($('#estimatedTaxesAndFees').val().replace(/,/gi,'')) || 0;
    var input3 = parseInt($('#downPayment').val().replace(/,/gi,'')) || 0;
    var input4 = parseInt($('#manufacturerRebate').val().replace(/,/gi,'')) || 0;    
    var input5 = parseInt($('#tradeInValue').val().replace(/,/gi,'')) || 0;
    var input6 = parseInt($('#amtOwedOnTrade').val().replace(/,/gi,'')) || 0;    
    var input7 = parseInt($('#extendedWarranty').val().replace(/,/gi,'')) || 0;
    var input8 = parseInt($('#gapInsurance').val().replace(/,/gi,'')) || 0;
    var input9 = parseInt($('#serviceContract').val().replace(/,/gi,'')) || 0;     

            $('.total').text(input1 + input2 + input3 + input4 + input5 + input6 + input7 + input8 + input9);

        //If I keep the following line and remove the ('input.number') function then it works fine.
//                      $('.total').text('$'+sum.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,'));

    var total = (input1 + input2 + input3 + input4 + input5 + input6 + input7 + input8 + input9);

     };
 });

});
//format the input fields displayed number
//If I keep these two functions below, then it does not display the formatted data correctly. 
$(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);

      $this.val(num2);
  });
});

function RemoveRougeChar(convertString){    

    if(convertString.substring(0,1) == ","){

        return convertString.substring(1, convertString.length)            

    }
    return convertString;

}
//restrict the keys
function isNumberKey(evt){    
    var charCode = (evt.which) ? evt.which : evt.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;
    return true;
};

Demo: http://jsfiddle.net/IrvinDominin/LHn6X/6/

Upvotes: 1

apohl
apohl

Reputation: 1923

You should look into using angularjs. It makes binding element values very simple.

Upvotes: 0

Related Questions