danyo
danyo

Reputation: 5846

jQuery get data from each loop and store in global variable

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?

Upvotes: 1

Views: 1838

Answers (2)

user6748331
user6748331

Reputation:

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())

Upvotes: 0

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

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.

Upvotes: 2

Related Questions