1

I have a HTML form with a text box that you can input a string like "1+2+8" and it will give you the total of the numbers.

My script is meant to add all of the numbers of the array "num" and alert the value. The problem is the alert displays NAN instead of the total. the values in num are floats but the alert still gives NaN. I have looked at this question but it is not the same problem. What could be causing this?

Here is the HTML/JS

<html>
  <head>
    <script type="text/javascript">


      function handleClick(event)
      {



        alert(this.textBox1.value);

        var num = this.textBox1.value.split("+"); 


        //convert string array to numbers
        for(var i=0; i<num.length; i++)
        {
            num[i] = +num[i]; 
        }

       // add up the values
        for(var i=0; i<num.length; i++)
        {
            var total = i + total;
        }
        alert(total); //Displays NaN instead of total



        event.preventDefault(); // disable normal form submit behavior
        return false; // prevent further bubbling of event
      }
      function doit()
      {

        document.forms.myform.addEventListener("submit", handleClick, true);
        return true;
      }
    </script>
  </head>


  <body onload="doit()">
    <form name="myform">
      <div>
          <textarea name="textBox1" rows="10" cols="80">
1+1
         </textarea>
      </div>
      <input type="submit" value="Update"/>

    </form>
  </body>
</html>
Community
  • 1
  • 1
Qwertie
  • 5,784
  • 12
  • 45
  • 89
  • 1
    In the first iteration of your loop, `i + total` is `0 + undefined` which is `NaN`. Hence any other operation results in `NaN`. You have to initialize `i` with a meaningful value. – Felix Kling Mar 16 '14 at 07:47

3 Answers3

3

Declare total variable outside the for loop and initialize it to 0. You also have to access the actually value in the array (num[i]), not the loop variable (i).

Here is the solution:

var total = 0;
for(var i=0; i<num.length; i++)
{
    total = num[i] + total;
}
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Bhavesh Munot
  • 675
  • 1
  • 6
  • 13
0

Try to explicitly parse it to float using parseFloat() function

eg

parseFloat("3.14");

You can read the documentation at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat

AurA
  • 12,135
  • 7
  • 46
  • 63
0

Use parseInt() function when converting string to Integer. And parseFloat for supporting non integer numbers.

dlyaza
  • 238
  • 2
  • 9