0

Found a couple of solutions for php, but couldn't find any for javascript.

Basically I am trying to make a bunch of eventlisteners for 30 buttons i have on my page. Currently it is written out like this :

problem1buttonEl.addEventListener("click", problem1);
problem2buttonEl.addEventListener("click", problem2);
problem3buttonEl.addEventListener("click", problem3);
problem4buttonEl.addEventListener("click", problem4);

Now I want to make a for loop to make this cleaner, something like this:

for (var problemIncrement = 1; problemIncrement <= 30; problemIncrement++) {
'problem' + problemIncrement + 'buttonEl'.addEventListener("click", 
'problem' + problemIncrement);
}

The problem is that i need to add a string to my variable and have the outcome of them also be a variable, as that is what problemXbuttonEl is.

Is there any way to do this?

Jorgen
  • 93
  • 1
  • 8

3 Answers3

1

Why not use a closure with an argument for the number of the identifier for the button like

function problem(n) {
    return function () {
        // do something with n
    }
}

for (var i = 1; i <= 30; i++) {
    getElementById('problem' + i + 'buttonEl').addEventListener("click", problem(i));
}
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

You can use the brackets notation [] to get these variables, normally they should be defined in the window object so this is how should be your code:

for (var problemIncrement = 1; problemIncrement <= 30; problemIncrement++) {
    window['problem' + problemIncrement + 'buttonEl'].addEventListener("click", 
    window['problem' + problemIncrement]);
}

Here window['problem' + problemIncrement + 'buttonEl'] will refer to the varibale you already defined.

cнŝdk
  • 31,391
  • 7
  • 56
  • 78
0
var resultsArray = [1, 2, 3];
var resultsString = myArray.join();
problem1buttonEl.addEventListener("click", function() {
  resultsArray.push(problem1)
});

document.write(resultsString);

or something like that!

Sandra Willford
  • 3,459
  • 11
  • 49
  • 96