Jump to content

NaN on Sum of Multiple Input Fields


dlebowski

Recommended Posts

Hello.  I am not a java expert and therefore do not understand why I keeping getting NaN for the total on this?  I understand that it is saying I am trying to add "non-number", but I can't figure out why this won't work.  Any help would be appreciated great.  Thanks

 

<script type="text/javascript"><!--
function updatesum() {
var elems = document.getElementsByClassName('toAdd');

var myLength = elems.length,
total = 0;
alert(myLength);
for (var i = 0; i < myLength; ++i) {
  total += elems[i].value - 0;
  
}

document.getElementById('sum').value = total;

}
//--></script>

<body>

<div  class="toAdd">
Enter a number:
<div><input id="Quantity[0]" onChange="updatesum()" /></div>
and another number:
<div><input id="Quantity[1]" onChange="updatesum()" /></div>

</div>
Their sum is:
<input id="sum" readonly style="border:0px;">

Link to comment
https://forums.phpfreaks.com/topic/261809-nan-on-sum-of-multiple-input-fields/
Share on other sites

your "elems" var consists of the entire "toAdd" div.. there is only 1 so no point in looping it, also div doesn't have "value" (you were trying elems.value)

 

take the class="toAdd" off of that div and put it on your inputs (which are the elements that have the values you want to add).

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.