0

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!

1
Contributor
1
Reply
2
Views
6 Years
Discussion Span
Last Post by lifeworks
1

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);
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.