0

I have got 3 buttons and I am trying to add their click behavior by pure Javascript dynamically, but seems an error is coming. Kindly, help:

<html>
<head></head>
<body>
<button id="btn-0">Button 1!</button>
<button id="btn-1">Button 2!</button>
<button id="btn-2">Button 3!</button>

<script type="text/javascript">
var prizes = ['A Unicorn!', 'A Hug!', 'Fresh Laundry!'];
for (var i = 0; i < prizes.length; i++) {
    // for each of our buttons, when the user clicks it...
    document.getElementById('btn-' + (i-1)).onclick = function() {
        alert(prizes[i-1]);
    };
}
</script>

</body>
</html> 

Please, help me understand how to dynamically bind events with 'getElementById'.

Deadpool
  • 7,811
  • 9
  • 44
  • 88
  • 1
    "an error is coming" - please share this error with us. – Lix May 21 '18 at 10:07
  • `for (var i = 0; i < prizes.length; i++) { (function (index) { // for each of our buttons, when the user clicks it... document.getElementById('btn-' + index).onclick = function () { alert(prizes[index]); }; })(i); }` – Satpal May 21 '18 at 10:08
  • "id" should be unique like the name already suggests... use classes or by tagname. – jvecsei May 21 '18 at 10:08

0 Answers0