I am trying to create a button in javascript that when clicked adds an item to a basket
heres my code
var imgSrc = new Array ("images/hangings/1.jpg","images/hangings/2.jpg");
var prices = new Array (100,50);
var sizes = new Array ("450*350","100*50");
function load()
{
if(displayProductInfo==true)
{
for (var i = 0; i < prices.length; i++)
{
$('#products ul').append('<li><img src="'+imgSrc[i]+'" width="525px" height="350px"/></li>');
$('#products ul').append('<li>Price: £' + prices[i] +'</li>');
$('#products ul').append('<li>Size: ' + sizes[i] +'</li>');
$('#products ul').append('<button type="button" onclick="addToBasket(i)">Add To Basket</button>');
}
}
}
function addToBasket(itemAdded)
{
alert("clicked")
}
Everything works fine, except when a button is clicked it doesn’t seem to run function addToBasket
whats wrong?
It’s because you can’t just call
addToBasket(i), becauseiin the scope of that function, doesn’t exist. You should change it to$('#products ul').append('<button type="button" onclick="addToBasket(' + i + ')">Add To Basket</button>');