Applying a function to different UI elements

My students are trying to create something similar to Wordle. The project is linked here

What I expect to happen:
What I want to do is take a very long function which changes the text in the read only text area and apply it to each text area in turn. We built a keyboard out of button elements, which I realize seems ridiculous, but if you’re familiar with Wordle, it eliminates letters as you find out they are not in the target word.

So what I want is function that I can use to run 26 event handlers (to check if the user has clicked a letter) and update the text in the first box to that one letter, then move on to the next box and do the same. Obviously that function is 52 lines of text, so I’m trying to to rewrite that function for each text box when there are currently 12 of them and a consideration for possibly adding more of them in the future.

What actually happens: / What I’ve tried:

The errors I’ve received are various because I’ve tried different solutions.
Screen Shot 2022-01-25 at 4.05.19 PM
What I really want is for the ID which currently say “current” to update with a variable. I’ve tried different ways of doing that, using a straight variable, using a list populated with the different options I need. Nothing has worked.

Is there a way to put a variable or other piece of code in that ID spot so that I can apply this function to different elements?

You could try this:

var letters = "abcdefghijklmnopqrstuvwxyz".split(""); // The split function turns a string into an array.
for (var i = 0; i < letters.length; i++) {
  onEvent(letters[i], "click", function (e) {
    setText("current", e.currentTargetId); // currentTargetId is helpful when using click events in an array
  });
}

It may warn you to not put functions in a loop, but ignore it.

Naming your individual buttons by the letter they represent is a good idea. @coffeya23 has given you some code to run through the letters and add event handlers. I would change that a bit by making a named function to handle the events.

var ALPHABET = "abcdefghijklmnopqrstuvwxyz".split("");

for (var i = 0; i < ALPHABET.length; ++i) {
  onEvent(ALPHABET[i], "click", letterWasPressed);
}

function letterWasPressed (event) {
  setText(current[currentIndex], event.currentTargetId);
}