1

I am writing some code to grab product id's and quantities before adding to my cart. I am looping through each product where the quantity is greater than 0, and then getting some information stored in the data attributes.

The issue i am having is outputting all of the data. here is my code:

jQuery( ".productList .catQuantity" ).each(function( index ) {
    var productID = jQuery(this).attr('data-product_id');
    var productQu = jQuery(this).attr('data-quantity');   
    if(productQu > 0){
        //console.log(productID+':'+productQu+',');
        window.allProducts = (productID+':'+productQu+',');
    }
});
console.log(allProducts);

So the above grabs the product id and quantity and stores it in a global variable. When i console.log the variable, only the last product added is included in the variable.

Any ideas why this is?

2 Answers 2

2

You should append them to the variable instead using +=, else the variable allProducts will be overwritten in every iteration of the loop :

window.allProducts += (productID+':'+productQu+',');

Hope this helps.

Sign up to request clarification or add additional context in comments.

Comments

0

Use array for storing all products, as you are appending unnecessary comma after last item. Then, if you need, just convert / show this array as string:

var allProducts = []

jQuery( ".productList .catQuantity" ).each(function( index ) {
  var productID = jQuery(this).attr('data-product_id')
  var productQu = jQuery(this).attr('data-quantity')  
  if (productQu > 0) {
    window.allProducts.push(productID + ':' + productQu)
  }
})

console.log(allProducts.toString())

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.