0

Consider the below code :

<button id="btn-0">Button 1!</button>
<button id="btn-1">Button 2!</button>
<button id="btn-2">Button 3!</button>
<button id="btn-3">Button 4!</button>
<script type="text/javascript">
    var prizes = ['Watch','A Unicorn!', 'A Hug!', 'Fresh Laundry!'];
    for (var btnNum = 0; btnNum < prizes.length-1; btnNum++) {
        // for each of our buttons, when the user clicks it...
        document.getElementById('btn-' + btnNum).onclick = function() {
            // tell her what she's won!
            alert(prizes[btnNum]);
        };
    }
</script>

I wanted it to work as on clicking different buttons, different array values should get appeared. But it alerts only "Fresh Laundry", whichever button is clicked. I'm not getting what's the issue here? Why every function expression assigned through for loop refers to the last element of prizes Array?

user3760959
  • 457
  • 1
  • 6
  • 18

1 Answers1

2

When you will click the value of btnNum will be the last value for all the click event handlers. So your events need to get the correct value.

You can put your event listener inside an Immediately Invoked Function Expression passing the value of btnNum.

var prizes = ['Watch', 'A Unicorn!', 'A Hug!', 'Fresh Laundry!'];
for (var btnNum = 0; btnNum < prizes.length - 1; btnNum++) {
  (function(el) {
    document.getElementById('btn-' + el).onclick = function() {
      alert(prizes[el]);
    };
  })(btnNum);
}
<button id="btn-0">Button 1!</button>
<button id="btn-1">Button 2!</button>
<button id="btn-2">Button 3!</button>
<button id="btn-3">Button 4!</button>
void
  • 36,090
  • 8
  • 62
  • 107