How to sum values stored in an array of textboxes

Hi all,

Please somebody tell me how to sum the values stored in an array of textbox using javascript and display it in a separate text box.

Thank you all.

Could you show us what you’ve got so far?

<script type=“text/javascript”>
function GrandTotal(){
var sum=0;
var cost = document.getElementsByName(‘totalcost’);
for(var i=0;i<cost.length;i++)
{
sum = sum+cost[i].value;
}
document.getElementById(‘grandtotal’).value = sum;
}

</script>

The above code does not shows the sum of the text box values.

Thank you for your help

could somebody see the above code and tell what I am doing wrong. All I want to do is to sum the array values that is coming from totalcost.

Here is where things are going wrong:

sum = sum+cost[i].value; 

In your for loop, if you run this:

alert(typeof cost[i].value) 

it will alert “string”. Since it’s a string, the plus (+) sign will be used to concatenate the string together instead of adding the values. You need to cast it to a number type by running either parseInt or parseFloat like so:

sum += parseFloat(cost[i].value); 

That should work.

Thank you. One more problem I am unable to call this function during body onload. Could please tell me how to call this function during body onload.

Thank you again.

You can load it using window.onload (which will wait until the window has loaded: images etc). This can only be used once as it will be over written the second time you call window.onload:

window.onload = GrandTotal;

Or if you want to tie in multiple window.onload events you can use this trick

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

addLoadEvent(GrandTotal);
addLoadEent(function(){ alert('another event loaded!'); });

Alternatively, most people use a framework like jQuery (www.jquery.com) and just have it run when the document has loaded. This method will not wait for images but will fire as soon as the DOM has finished loading:

$(document).ready(GrandTotal);

The other alternative is to put the script call for this function just before the </body> tag. :slight_smile: