Reputation: 45
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?
Upvotes: 0
Views: 312
Reputation: 6605
you don't need new Array(...)
- [...]
is enough.
doing $('#products ul')
more than once is bad. you do it 4 times in a single iteration. store it in a variable and reuse it: var list = $('#products ul');
and the reason why it probably fails - as the others wrote - you don't pass the value of i
but instead try to read i
when you click the button.
var imgSrc = ["images/hangings/1.jpg", "images/hangings/2.jpg"],
prices = [100, 50],
sizes = ["450*350", "100*50"];
function load() {
if (displayProductInfo) {
var list = $('#products ul');
for (var i = 0; i < prices.length; i++) {
list.append('<li><img src="' + imgSrc[i] + '" width="525px" height="350px"/></li>');
list.append('<li>Price: £' + prices[i] + '</li>');
list.append('<li>Size: ' + sizes[i] + '</li>');
list.append('<li><button type="button" onclick="addToBasket(' + i + ')">Add To Basket</button></li>');
}
}
}
function addToBasket(itemAdded) {
alert("clicked");
}
Upvotes: 0
Reputation: 27839
Try this:
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 />', {'data-item': i}).text('Add To Basket').click(addToBasket));
}
}
}
function addToBasket()
{
alert("clicked on " + $(this).attr('data-item'));
}
var displayProductInfo = true;
load();
Look at it working here.
Upvotes: 0
Reputation: 10931
It's because you can't just call addToBasket(i)
, because i
in 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>');
Upvotes: 1