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 trialilovecode
8,071 PointsPush items into an to array upon each click of button not working
I have the following code (I have simplified it as much as possible).
When I click on the add to cart button each price for the product gets added to the cart dropdown in my menu. In my total() function I would like to insert each price into an array as I click to add products, so that I will eventually calculate the total. For now I just want to create the array.
My problem is as follows: If a price is 3.27 then it logs [3.27] and when I click again and let's say the price is 2.00 next then it creates new array of [2.00], but does not add items together to be [3.27, 2.00].
I know it does not look like I have done much in my total() function but I have tried different things (loops, concat etc), even ridiculous stuff that I knew won't work.
I am now not sure if it is because of the looping of the button, or what. I tried loops inside the total function as well.
function addToCart(data) {
let addToCartBtn = document.querySelectorAll('.addtocart');
for (let i = 0; i < addToCartBtn.length; i++) {
addToCartBtn[i].addEventListener('click', (e) => {
e.preventDefault();
id = data[i].id
if (data[i].id === id) {
section.innerHTML = <span class="cart-price price text-info">${data[i].price}</span>
`);
}
total(data[i].price);
});
}
}
function total(price) {
// This function will eventually display a total of the items added, but I want to insert the prices into an array for now.
let total = 0;
let prices = [];
prices.push(price);
console.log(prices); //logs an array each time
}
1 Answer
John McGarvey
14,026 PointsYou need to do the let prices = []; outside of the total function. Every time that function is called, it is reinitializing the array to [].
ilovecode
8,071 PointsI knew it was something really stupid. Thanks a lot
John McGarvey
14,026 PointsJohn McGarvey
14,026 PointsYou need to do the let prices = []; outside of the total function. Every time that function is called, it is reinitializing the array to [].