Neesh
Neesh

Reputation: 87

button for each item in array and different output for each

I have 3 parallel arrays: fruit, colour, and shape

I would like each of the fruits to be a button. When the button is pressed the colour and shape of the fruit displays below. I have managed to display the buttons but when run only the last colour and shape are displayed as an alert when the buttons are pressed.

Here's my code:

var fruit = ["apples", "bananas", "oranges"];
var colour = ["red", "yellow", "orange"];
var shape = ["round", "long", "round"];

for(i = 0; i < fruit.length; i++) {
   holder = colour[i] + shape[i];
   document.getElementById("foo").innerHTML += "<button onclick='alert(" + 'holder' + ")'>" + fruit[i] + "</button>";

it does not seem to work when putting the colour and shape straight into the alert instead of the holder as shown:

document.getElementById("foo").innerHTML += "<button onclick='alert(" + 'colour[i] + shape[i]' + ")'>" + fruit[i] + "</button>";
//does not work

note: the arrays are much longer so it would not work to do each item separately. Also it would be better if the colours and shapes were displayed below instead of in a alert.

thanks in advance!

Upvotes: 0

Views: 711

Answers (2)

kkmazur
kkmazur

Reputation: 506

You'are overriding on each loop iteration the global holder variable. So at the end of the processing the loop the holder variable holds the last values in the iteration ie. orangeround.

You need either embedd the value in the alert at the moment of creation or reference the correct state like:

"<button onclick='alert(\"" + holder + "\")'>" + fruit[i] + "</button>";

or create an object which you can reference ie.:

var fruit = ["apples", "bananas", "oranges"];
var colour = ["red", "yellow", "orange"];
var shape = ["round", "long", "round"];
var holder = {};
for(let i = 0; i < fruit.length; i++) {
   holder[i] = colour[i] + shape[i];
   document.getElementById("foo").innerHTML += "<button onclick='alert(" + 'holder['+i+']' + ")'>" + fruit[i] + "</button>";
}

Upvotes: 1

Taplar
Taplar

Reputation: 24965

var fruit = ["apples", "bananas", "oranges"];
var colour = ["red", "yellow", "orange"];
var shape = ["round", "long", "round"];

for(i = 0; i < fruit.length; i++) {
   holder = colour[i] + shape[i];
   document.getElementById("foo").innerHTML +=
     '<button onclick="alert(\''+ holder + '\')">' + fruit[i] + '</button>';
   }
<div id="foo"></div>

Your issue is that your onclick is not being constructed properly, and is using the holder as a variable, instead of putting the literal string it has for each iteration into the onclick alert call. Fixing the construction of the onclick makes it use the literal value it was constructed with, instead of the global variable.

Upvotes: 1

Related Questions