Reputation: 6493
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>
Upvotes: 1
Views: 3346
Reputation: 675
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;
}
Upvotes: 2
Reputation: 238
Use parseInt()
function when converting string to Integer. And parseFloat
for supporting non integer numbers.
Upvotes: 0
Reputation: 12363
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
Upvotes: 0