0

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

2 Answers 2

1

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/

Sign up to request clarification or add additional context in comments.

1 Comment

That gets me part way there. Thank you.
0

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

2 Comments

Indeed and I already have. But already using jQuery and JQuery UI within the core code so trying not to put too many other script libraries in there. That's why I have not put in Angular or Knockout yet.
Ok. I would definitely not advise using angularjs with JQuery Mobile UI. It gets really messy because of how JQuery Mobile generates elements.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.