Page 1 of 1

Adding up values with javascript

Posted: Tue Nov 14, 2006 4:57 am
by Wardy7
I have some javascript on a site that depending on what number a user selects from a drop down menu it displays a price for it.
I have it so that the user can select a number of different quantities for different items with the result of each one being displayed in a textbox.
However I also want there to be another text box that adds up all the values that are displayed automatically but I'm struggling to get this to work, can anyone help...

Below is the code I use to do the working outs for the individual items and this would display it's result in text box "total1"

Code: Select all

<script type="text/javascript"> 
function calcForm(form,submit_it) { 
// By making the first element 0, this associates the list precisely with the select list. 
// To maintain all you need to do is change this array. 
var prices = new Array('0.00','16.00','24.00','32.00','40.00'); 
var sel = document.getElementById('num'); // The list 
var ind = sel.selectedIndex; // What's selected 
var total = document.getElementById('total1'); 
total.value = prices[sel[ind].value]; // the correlating value from the array 
if (ind == 0) { return; } 
if (submit_it) { form.submit(); } 
} 
</script>
Can anyone help, it's doing my head in but I htink ti shouldn't be too hard to do but I don't really use javascript much so I can't get it to work!
I hope this all makes sence!

Cheers
Wardy

Posted: Tue Nov 14, 2006 7:13 am
by Chris Corbyn
If you collect all the chosen values in an array you can loop over them to add them up, for example:

Code: Select all

var chosen = new Array();
chosen.push(15);
chosen.push(12.7);
chosen.push(3);

/**
 * Get the sum total of all values in the array
 * @param {array} float
 * @returns {float}
 */
function getSum(arr)
{
    var total = 0;
    for (var i in arr) total += parseFloat(arr[i]);
    return total;
}

alert(getSum(chosen)); //30.7