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
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).

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.