1

I'm using jquery to calculate sum of value of input box. but my code only show entered value and don't show the sum of numbers in total.

$(document).ready(function() {
    $('input').change(function(e) {
        var total_amnt = 0;
        var fcharge1 = ($('#fcharge').val());
        var lrcharge1 = ($('#lrcharge').val());
        var loadingcooly1 = ($('#loadingcooly').val());
        var othercharge1 = ($('#othercharge').val());
        var crossforothers1 = ($('#crossforothers').val());
        var cashpaid1 = ($('#cashpaid').val());
        var doorcollection1 = ($('#doorcollection').val());
        var transhipment1 = ($('#transhipment').val());
        var advanceamt1 = ($('#advanceamt').val());
        var stax1 = ($('#stax').val());
        var cess1 = ($('#cess').val());
        var rebooking1 = ($('#rebooking').val());

        total_amnt = fcharge1 + lrcharge1 + loadingcooly1 + othercharge1 + crossforothers1 + 
        cashpaid1 + doorcollection1 + transhipment1 + advanceamt1 + stax1 + cess1 + 
        rebooking1;

        $('#totamt').val(total_amnt);
    });
}); 
Yeldar Kurmangaliyev
  • 33,467
  • 12
  • 59
  • 101
Sail
  • 129
  • 1
  • 10

2 Answers2

1

The reason is that .val() returns string value of an element.

As the result, here

total_amnt = fcharge1 + lrcharge1 + loadingcooly1 + othercharge1 +   crossforothers1 + cashpaid1 + doorcollection1 + transhipment1 + advanceamt1   + stax1 + cess1 + rebooking1;

you concatenate strings, but not integers.

console.log(1 + 3 + 6); // 10 
console.log('1' + '3' + '6') // '136'

You need to convert every value into an integer. The easiest way is to add unary + before a string:

var fcharge1 = +$('#fcharge').val();
var lrcharge1 = +$('#lrcharge').val();
var loadingcooly1 = +$('#loadingcooly').val();
var othercharge1 = +$('#othercharge').val();
var crossforothers1 = +$('#crossforothers').val();
var cashpaid1 = +$('#cashpaid').val();
var doorcollection1 = +$('#doorcollection').val();
var transhipment1 = +$('#transhipment').val();
var advanceamt1 = +$('#advanceamt').val();
var stax1 = +$('#stax').val();
var cess1 = +$('#cess').val();
var rebooking1 = +$('#rebooking').val();

Note that it is just an example and it is subject to checks, validations and other improvements.

Read more about how to convert string into an integer in this great article:
How do I convert a string into an integer in JavaScript?

Community
  • 1
  • 1
Yeldar Kurmangaliyev
  • 33,467
  • 12
  • 59
  • 101
1

Before adding numbers use parseFloat and check for if the value is number

Something like

 var fcharge1 = ($('#fcharge').val());
 if(isNaN(fcharge1) || fcharge1.length ==0) {
   fcharge1=0;
  }



  var lrcharge1 = ($('#lrcharge').val());
if(isNaN(lrcharge1) || lrcharge1.length ==0) {
   lrcharge1=0;
  }

Similarly do for each text box and then add it like that

total_amnt = parseFloat(fcharge1) + parseFloat(lrcharge1) + parseFloat(loadingcooly1)...;

This might help you.

F11
  • 3,703
  • 12
  • 49
  • 83