How can I get this to work?


probably too simple, but since I am an absolute JS novice I don’t know how to fix it.
Here’s the problem:
If I click the color button, colors are in the txt boxes. If I click the name button, colors are in the txt boxes again. When I remove the first break in the JS , both buttons give the same “I , you, he” result.
TIA (17.3 KB)

Note about your issue:

If you do want to use an if clause you should do it without the for loop and match the button id directly with a string.

This is another way of doing it.

I use the ID’s of the buttons in an eval() to get the correct array. Then populate the text fields.

I just made this up so I am not sure how well this will stand up. But it works.

  var TextColor = ["red", "green", "blue"]
    	var TextName = ["I", "you", "he"]
            var  buttonID =;
hypeDocument.getElementById("text1").innerHTML = eval([buttonID][0])[0];
hypeDocument.getElementById("text2").innerHTML = eval([buttonID][0])[1];
hypeDocument.getElementById("text3").innerHTML = eval([buttonID][0])[2]; (20.4 KB)

Here is a second way to do it without a for loop.

This gets the ID of the clicked button and the index of the matching object in the buttonNames array.

It then uses that to choose the correct array ( names or colours) in the colorAndNames array and populate with the resulting arrays objects.

var colorAndNames = [["red", "green", "blue"],["I", "you", "he"]]
	var buttonNames = ['btcolor', 'btname']
  var buttonID =;
   var index = buttonNames.indexOf(buttonID);
 hypeDocument.getElementById("text1").innerHTML = colorAndNames[index][0];
 hypeDocument.getElementById("text2").innerHTML = colorAndNames[index][1];
 hypeDocument.getElementById("text3").innerHTML = colorAndNames[index][2];

Thank you very much Mark. It’s been very helpful. I think I will be using the first solution.

Cheers, Djon

On second thought I will use the other one. :smiley:
More convenient for what I want to achieve.

1 Like