Ashish Poudyal Ashish Poudyal - 16 days ago 5
Javascript Question

Number concatenates instead of being added

Everything works fine on my code until I enter a value for shipping it concatenates to the result instead of addition.

function subtotal(){
var a,b = 0;
var row = $('#tbody tr').not(':first-child').length;
for(i=0;i <= row;i++){
a = parseFloat($('#i-total'+i).val());
b += a;
}
$('#sub-total').val(parseFloat(Math.round(b * 100) / 100).toFixed(2));
$('#sub-total').attr('value',parseFloat(Math.round(b * 100) / 100).toFixed(2));

var dis = $('#disc-val').val();
$('#disc-val').attr('value',dis);
var tax = $('#tax').val();
$('#tax').attr('value',tax);
if(tax == '' || dis == ''){
tax = 0;
tax = parseFloat(tax);
dis = 0;
dis = parseFloat(dis);
}
var stat1 = $('#disc-val').attr('data-stat');
if(stat1 === 'on'){
b = b-(b*dis/100);
// console.log('disc%'+z);
}
else if(stat1 === 'off'){
b = b - dis;
// console.log('disc'+y);
}
var stat2 = $('#tax').attr('data-stat');
if(stat2 === 'on'){
b = (b*tax/100)+b;
}
else if(stat2 === 'off'){
b = b + tax;
}

var ship = $('#shipping-val').val();
$('#shipping-val').attr('value',ship);
if(ship == ''){
ship = 0;
ship = parseFloat(ship);
}

b = (ship + b);

$('#whole-total').attr('value', b);
}

Answer

try to use below way

 if(ship == ''){
        ship = 0;
        ship = parseFloat(ship);
    }

    b = parseFloat(ship) + parseFloat(b);