I have declared a global variable
var cart = [];
var cartTotal;
$(document).ready(function()
{
if(typeof cartTotal != 'undefined')
{
alert(cartTotal);
}
else
{
alert("cartTotal is undefined");
}
loadJSON();
});
I then change it in a function later down the line after going through loadJSON etc.
function addToBasket(item)
{
$.getJSON("products.json", function(result)
{
for (var i in result.products)
{
var itemToAdd = result.products[i].idCode;
if(item == itemToAdd)
{
if(typeof cartTotal == 'undefined')
{
cartTotal = "";
cartTotal = cartTotal + parseFloat(result.products[i].price);
document.getElementById("currentTotalCost").innerHTML = "£" + cartTotal;
}
else
{
cartTotal = parseFloat(cartTotal) + parseFloat(result.products[i].price);
document.getElementById("currentTotalCost").innerHTML = "£" + cartTotal;
}
}
}
});
cart.push(item);
alert(cart);
}
But when I then try and access the cartTotal elsewhere in another function after changing the value, it's throwing an undefined message, and I'm totally stumped as to why. I've tried setting an alert when it runs loadJSON again, as I know when that will run, but it's just saying undefined, even after going there from the addToBasket.