SBB
SBB

Reputation: 8970

get sum of number is causing NaN

I have a function that is adding up 6 total fields from a form and putting it in the grand total section. However, until all 6 fields are filled in, grand total shows NaN as the fields are empty until the end.

How would I go about making this total show up based on the totals it has at any given time.

function CalculateGrandTotal(){

var total1 = parseInt($('#classTotal1').val()),
    total2 = parseInt($('#classTotal2').val()),
    total3 = parseInt($('#classTotal3').val()),
    total4 = parseInt($('#classTotal4').val()),
    total5 = parseInt($('#classTotal5').val()),
    total6 = parseInt($('#classTotal6').val()),
    final = total1 + total2 + total3 + total4 + total5 + total6;

    $('#grandTotal').val(final);    
}

Upvotes: 0

Views: 129

Answers (4)

Milind Anantwar
Milind Anantwar

Reputation: 82231

That is because parseInt('') returns Nan.Try like this:

var total1 = parseInt($('#classTotal1').val()) || 0;

Working Demo

Upvotes: 1

Ashima
Ashima

Reputation: 4824

var total1 = parseInt($('#classTotal1').val().replace(/^\s+|\s+$/g, '')) || 0;

strip out empty space and if it is empty, give it 0

Upvotes: 0

tadman
tadman

Reputation: 211560

If any one of those values is undefined you're going to get a NaN value messing up your calculations. A single one will spoil the party.

It might be better to do this:

var total = 0
var i

for (i = 1; i <= 6; ++i) {
  var val = $('#classTotal' + i).val();

  if (val) {
    total += parseInt(val)
  }
}

Use loops rather than copy-pasting tons of lines of code.

Upvotes: 0

Soren
Soren

Reputation: 14688

You could try to default the unparseble values to zero, like this

var total1 = parseInt($('#classTotal1').val()) || 0,
    total2 = parseInt($('#classTotal2').val()) || 0,
    total3 = parseInt($('#classTotal3').val()) || 0,
    total4 = parseInt($('#classTotal4').val()) || 0,
    total5 = parseInt($('#classTotal5').val()) || 0,
    total6 = parseInt($('#classTotal6').val()) || 0;
var final = total1 + total2 + total3 + total4 + total5 + total6;

Upvotes: 5

Related Questions