Hi

Im processiing a json response

link_cart.setAttribute('id',bits[i].product_id);

link_cart.onclick = function(){
    add_to_cart(bits[i].product_id);
}

In the first line, the product_id value is correct, the json is a list of products, but it doesn't behave strangely,

But the second reference in the onclick handler, displays a value of 22, which is the product_id of the last of 22 products...

I feel im missing a small, key piece of info here...

Help!

I solved it myself!

Found this article http://www.howtocreate.co.uk/referencedvariables.html

Seems that the problem is the onclick handler is executed in the context of my for() loop being completed... so you need to pass those variables out of the loop to another function, which returns a function which uses your variables, but preserves them...

//function which preserves vars
function preserver_addtocart(pid){
     return function(){
          add_to_cart(pid);
     };
}

//loop loooking through my json response
for(var i in bits){
     link_cart.onclick = preserver_addtocart(bits[i].product_id);
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.