Moorani
Moorani

Reputation: 129

Sum of input fields into #total readonly field

I have a jquery function on keyup which calculates number of boys enrollments in different classes (using fields) and puts the sum in total boys enrollment field.

$("#Asc201516EleClassEceBoysEnrollment").keyup(function(){
            var sum = 0;

            ece    = +$("#Asc201516EleClassEceBoysEnrollment").val();               
            katchi = +$("#Asc201516EleClassKatchiBoysEnrollment").val();
            one    = +$("#Asc201516EleClassEceOneEnrollment").val();
            two    = +$("#Asc201516EleClassEceTwoEnrollment").val();
            three  = +$("#Asc201516EleClassThreeBoysEnrollment").val();
            four   = +$("#Asc201516EleClassFourBoysEnrollment").val();
            five   = +$("#Asc201516EleClassFiveBoysEnrollment").val();
            six    = +$("#Asc201516EleClassSixBoysEnrollment").val();
            seven  = +$("#Asc201516EleClassSevenBoysEnrollment").val();
            eight  = +$("#Asc201516EleClassEightBoysEnrollment").val();
            nine   = +$("#Asc201516EleClassNineBoysEnrollment").val();
            ten    = +$("#Asc201516EleClassTenBoysEnrollment").val();

            sum =  sum + parseInt(ece+katchi+one+two+three+four+five+six+seven+eight+nine+ten);             
            console.log(sum);

            $("#Asc201516EleTotalBoysEnrollment").val(sum);

        });

I get NaN in #Asc201516EleTotalBoysEnrollment input field. What could be the issue? Same function is working fine for other group (teachers total) of fields on the same page.

Upvotes: 0

Views: 195

Answers (1)

Carsten Massmann
Carsten Massmann

Reputation: 28196

If you don't need to keep the individual counts in their global variables, as shown in your example (did you declare these variables anywhere with var ...?!?) then you could instead do the whole thing with this slighty shorter function:

$("#Asc201516EleClassEceBoysEnrollment").keyup(function(){
  var sum=0
  ['ece','katchi','one','two','three','four','five','six','seven','eight','nine','ten'].forEach(function(el){
      sum += ~~$("#Asc201516EleClass"+el+"BoysEnrollment").val();
  })
  console.log(sum);
  $("#Asc201516EleTotalBoysEnrollment").val(sum);
});

In JavaScript ~ is the bitwise NOT-Operator. Applying it twice will turn any string into an integer value and can therefore be seen as the "more tolerant brother" of the standard parseInt() function. NaN will appear as 0 and float values will be truncated.

( Applying the + operator on each string returned by .val(), as you did it, will also try to convert a string into an integer, but if the string contains any characters not compatible with an integer format the result will be NaN and ultimately spoil your summation. )

Upvotes: 1

Related Questions