Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Javascript product quantity option

Hi all,

In my project I have a shopping cart which has a quantity option for each product in the cart, and then a total price at the end. I need to update the total price based on the quantity of each product. Problem is I'm not very good at Javascript so I was wondering if anyone could suggest how I can get something like this working?

Thanks, Adam

1 Answer

geoffrey
geoffrey
28,736 Points

Why not having for each product an array with for exemple the name or id, price and quantity ? Such as this:

var productsInCart = [{"id":1,"price":25,"quantity":5}, {"id":2,"price":5,"quantity":1},{"id":3,"price":8,"quantity":1}];

Then you could just create a loop to multiply the cost of each product by Its quantity and then you add up everything...

    var totalCost = 0;

    for (var product in productsInCart){
         totalCost = totalCost+(productsInCart[product].price * productsInCart[product].quantity);
     }

Here is the link to js fiddle. http://jsfiddle.net/Azuk/0ab55tcz/, hope that helps.