1

I am currently in the process of re-writing most of my code to accommodate Content Security Policy. As such i am in the process of removing all inline code. I am currently using a bootstrap modal to display results of an AJAX call with javascript. The problem seems to be in reading my array? When it populates Event Listeners it will only ever link to the last item in the array

Example :

GIVEN -

numberArray [1, 2, 3, 4, 5]

targetButton ["btnTarget1", "btnTarget2", ...., "btnTarget5",]

Javascript.js

for(var i = 0; i < numberArray; i++)
{
    document.getElementById(targetButton[i]).addEventListener("click", function(){loadSpecificButtonResults(numberArray[i]);}, false)
}

I have changed syntax around to try different things.

var currentSelection = targetButton[i]
document.getElementById(currentSelection).addEventListener("click", function(){loadSpecificButtonResults(numberArray[i]);}, false)
}

But no matter what i do, even if i attach event listeners to my buttons, they will ALWAYS result in calling the method with the last item in the array?

ex-

btnTarget1 - loadSpecificButtonResults(5)

btnTarget2 - loadSpecificButtonResults(5)

btnTarget3 - loadSpecificButtonResults(5)

btnTarget4 - loadSpecificButtonResults(5)

btnTarget5 - loadSpecificButtonResults(5)

I think instead of interrelating through each button, the call is simply applying 1 item to ALL buttons in one call? I just cant figure out where i am going so wrong here ^?

Any help would be appreciated! Thank you for your time

Morjee
  • 89
  • 9
  • Thank you so much to @CertainPerformance. This wizard pointed out my whole flaw instantly. Using .forEach does all the heavy lifting. Thank you so much. – Morjee Nov 25 '19 at 05:31

0 Answers0