What causes the same Array value to appear when clicking on various buttons?

Take a look at the code snippet below:

<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++) {
        // when any button is clicked...
        document.getElementById('btn-' + btnNum).onclick = function() {
            // display the corresponding prize from the array
            alert(prizes[btnNum]);
        };
    }
</script>

The intention was to show different array values on clicking different buttons. However, regardless of which button is clicked, only "Fresh Laundry" appears in the alert. There seems to be an issue here where each function assigned in the loop points to the last element in the prizes Array. Why is this happening?

Answer №1

When you click, the value of btnNum will remain as the last value for all click event handlers. Therefore, it is important to ensure that your events are getting the correct value.

To solve this issue, you can encapsulate your event listener within an

Immediately Invoked Function Expression
and pass the value of btnNum as a parameter.

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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I noticed a change in the state between dispatches, but I did not make any alterations to the state

Although this question has been previously raised, most of the discussions focus on the OP directly mutating the state. I have taken precautions to avoid this by using techniques like the spread operator with objects and arrays. However, despite these effo ...

Modify the href attribute of an anchor tag that does not have a specified class or

I am currently using an event plugin that automatically links all schedule text to the main event page through anchor tags, like this: <td><a href="http://apavtcongresso.staging.wpengine.com/event/congresso-apavt-2018/">Chegada dos primeiros c ...

Utilizing MongoDB Data in an .ejs Template Using Node.js Express

After going through numerous tutorials, I find myself stuck at a point where I am struggling to render all the data written by my express-app into MongoDB in embedded JavaScript. My goal is to display this data in a simple table that always shows the updat ...

Processing ajax requests in Rails 4 using HTML format

I'm currently in the process of setting up ajax functionality for my contact form and I am currently testing to ensure that the ajax call is being made. When checking my console, I noticed that it is still being processed as HTML and I cannot seem to ...

Submitting form by clicking a link on the page

To submit a POST request with "amount=1" without displaying it in the URL, I need the site to send this request when any link on the site is clicked. This JavaScript code achieves that with a GET request: window.onload = function () { document.body.oncli ...

Issue with reflect metadata in Next.js edge runtime causing functional problems

Currently, I am utilizing a package in my upcoming 13 app that incorporates reflect metadata. Unfortunately, during the next build process, an error occurs for which I haven't been able to find a solution. ../../eshop-sdk-js/node_modules/reflect-metad ...

Imitate a worldwide entity with Jest and Typescript

I have a React component that utilizes the global object Routes provided by the Rails gem js-routes. My component is being tested with Jest's snapshot testing feature. The issue arises when trying to mock the Routes global object in the test to return ...

ng-class will not activate a custom directive

I have developed a custom AngularJS directive that should work on elements with the specified class name .collapse. However, when I apply this class using Angular's ng-class directive, the custom collapse directive does not get activated. Here is a ...

How can I retrieve the value of a particular key within a string using Swift?

After receiving a server response, I'm trying to access specific data within it. ( { agreementId = "token.virtual.4321"; city = AMSTERDAM; displayCommonName = "bunch-of-alphanumeric"; displaySoftwareVersion = "qb2/ene/2.7.14"; ...

Error in Nestjs Swagger: UnhandledPromiseRejectionWarning - The property `prototype` cannot be destructed from an 'undefined' or 'null' object

Currently, I am in the process of developing a Nestjs REST API project and need to integrate swagger. For reference, I followed this repository: https://github.com/nestjs/nest/tree/master/sample/11-swagger However, during the setup, I encountered the foll ...

Using Vue.js to bind labels and radio buttons in a form

My goal is to generate a dynamic list of form polls based on the data. However, using :for or v-bind:for does not result in any HTML markup appearing in the browser, causing the labels to not select the corresponding input when clicked. I have prepared a J ...

Searching for the initial occurrence of a certain value within a multi-dimensional array of objects using Java 8

Exploring the functionality of Java 8 features, I decided to experiment with multidimensional arrays of objects. My goal was to identify the first occurrence of a specific value in such an array. Objects[][] someArray= ..... Arrays.stream(someArray) ...

Protecting Node.js Files

As I prepare to embark on creating a new website, my main goal is to collect form input values such as dropdowns and radio boxes from the client without requiring user accounts. These values will be used for sensitive calculations, making security a top pr ...

Exploring the 3D Carousel Effect with jQuery

After creating a 3D carousel using jQuery and CSS3, I am looking to enhance it with swiping support. While there are plenty of libraries available for detecting swipes, I specifically want the carousel to start rotating slowly when the user swipes slowly. ...

Is there a way to create an internal link to another HTML templating engine page within Express.js?

I am currently facing an issue with two Pug files, index.pug and search.pug, stored in a /views folder. In my index.pug file, I have the following line of code: a(href="/search.pug") Search In my JavaScript file, I have specified the view engine as P ...

The React context is currently yielding an undefined value

I am puzzled by this issue. I have double-checked to ensure that the states value is not undefined, and it isn't. However, I am unable to pinpoint where I may be making a mistake. Here is my authContext.js file: const initialState = { isAuthorized: ...

tips on incorporating chosen while still enabling text input

I am currently utilizing chosen to showcase a single selection from a lengthy array of choices. In addition, I am seeking the functionality to enable users to submit a choice that is not listed among the available options. This customization is specifica ...

Trouble with Updating InnerHTML

xmlHttp = new XMLHttpRequest(); xmlHttp.open( "GET", "myurlhere.php", true ); xmlHttp.send(); var display = document.getElementById("display"); display.innerHTML = xmlHttp.response; This snippet of code is part of a function triggered by a button click. ...

The function is missing from the object, leading to a script error with jQuery

When using different versions of jQuery, I encountered some issues with saving changes in my application. Initially, with jquery-1.4.4.min.js, everything worked except for the save function due to an error I made. However, when switching to jquery-1.7.1.mi ...

Scraping dynamic content with Python for websites using JavaScript-generated elements

Seeking assistance in using Python3 to fetch the Bibtex citation produced by . The URLs follow a predictable pattern, enabling the script to determine the URL without requiring interaction with the webpage. Attempts have been made using Selenium, bs4, amon ...