Question

all! I've come across a dilemma. I'm creating something of a price-configurator, and basically Jquery is going to be creating a bunch of subtotal variables as the user selects certain options. All of these variables will have names that begin with sub- At the end of the code, I'd like to be able to write a line that gets each one of the sub- variables and adds its value to a grand total. Is there a way to do this, and if so, how?

Was it helpful?

Solution

There is not really a way to do this if the variables are tracked separately. If you stored them in an object, you can loop through the object using

$.each(myObject, function (key, value) { 
    if (key.indexOf('sub-') === 0) { 
        // to do 
    } 
});

You can do this with an array, and use

myArray[myArray.length] = value

as you are looping through the form. Then loop through the array at the end to get the values you need.

OTHER TIPS

Without seeing your code or pseudo-code or knowing anything about the scope of your price configurator, is there any reason why you can't create a (relatively) global grand-total variable that is accessible, scope-wise, to every code path that generates a sub- variable; and then add the value of each sub- variable to the grand total as soon as the value of the sub- variable is calculated?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top