Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Add values of array

Status
Not open for further replies.

project3

Technical User
Jan 10, 2008
22
US
Ok. me again I know I know.

I have input boxes named name[] to make them an array.

How would I add the values of the array to get a total.

And there will never be the same number in the array.

sometimes there may be 3 text boxes sometimes 8.

in php I know I can get a count of values in the array. but not sure on in javascript.
 
To total the values in an array loop through the array adding each value to a total variable
Code:
var total = 0;
for(var i = 0; i < myArray.length; i++){
 total += myArray[i];
}

of course if there is a change there will be string values in there (if say you're pulling them out of input fields) you will need to verify what you are adding together are both numbers with [tt]parseFloat[/tt] or [tt]parseInt[/tt].

Code:
var total = 0;
for(var i = 0; i < myArray.length; i++){
 var thisVal = parseInt(myArray[i]);
 if(!isNaN(thisVal)){
  total += thisVal;
 }
}

Never be afraid to share your dreams with the world.
There's nothing the world loves more than the taste of really sweet dreams.

Webflo
 
you are awesome dwarfthrower !! thats what i needed.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top