retrieving object attributes within a loop-contained function

I've been working on adding a click event to a specific div that I created. While I was successful in doing so, the problem arises when I click on it and it displays undefined.

Below is the code snippet:

The variable 'resulta' is declared as a global array with objects


for(s = 0; s < resulta.length; s++) {
    y = document.createElement('div');
    y.setAttribute('class', 'eachssd');
    var x = document.createTextNode(resulta[s].name);
    y.appendChild(x);
    o.appendChild(y);
    y.addEventListener('click', function bnmhv() {location.href=resulta[s].datasrc}, false);
}

Thank you in advance for any help!

Answer №1

Each time the for loop runs, all the event listeners that are created refer to the same s variable. This means that after each iteration, the value of resulta.length is assigned to s, resulting in resulta[s] being undefined. In order to fix this issue, you need to create a new scope for each of your event handlers by enclosing them in a closure. This way, each handler can access the correct value from

resulta[<current iteration's s value>]
.

Here is an example:

for(var s = 0; s < resulta.length; s++)
{
    (function (data) {
        var y = document.createElement('div')
        y.setAttribute('class', 'eachssd');
        var x = document.createTextNode(resulta[s].name)
        y.appendChild(x);
        o.appendChild(y)

        y.addEventListener('click', function () { location.href = data.datasrc }, false);
    }(resulta[s]));
}

During each iteration, an anonymous function is created and immediately invoked with the argument being

resulta[<current iteration's s value>]
, which is stored in the data parameter. When a user clicks on one of the created div elements, the click handler will reference data from its lexical scope.


For more information, check out these resources:

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

Retrieve a variety of items and pass them to a view using the mssql module in Node

I'm facing an issue while trying to retrieve data from multiple tables and pass them to my view. Below is the snippet of code I've written that's causing the error. router.get('/', function(req, res, next) { sql.connect(config ...

The dynamic concatenation of Tailwind classes is failing to have any effect, even though the full class name is being

I'm currently using Tailwind CSS within my Next.js project and I have a common method that dynamically returns the desired background color. However, despite adding the full class name, the background color is not displaying as expected. After reading ...

Tips for eliminating unnecessary module js calls in Angular 9

https://i.sstatic.net/3R7sr.png Utilizing a lazy loading module has been efficient, but encountering challenges with certain modules like all-access-pass and page not found as shown in the image above. Is there a way to effectively remove unused module J ...

Exploring the variable scope in Node.js with a focus on separating routes

My routing configurations are stored in an external folder. Find them in the ./routes directory This is how I set up my routes within the server.js file: app.get('/', routes.index); app.post('/validation', register.valid); The reg ...

Automatically scroll the element both up and down

I am working on a bootstrap table that needs to automatically scroll vertically. The table will be displayed on a screen and could have varying numbers of items, so I want it to continuously auto-scroll for the user's convenience. Once it reaches the ...

What is the best way to split an input field into distinct fields for display on the screen?

Take a look at this image: https://i.stack.imgur.com/LoVqe.png I am interested in creating a design similar to the one shown in the image, where a 4 digit one-time password (OTP) is entered by the user. Currently, I have achieved this by using 4 separate ...

Implementing Object.somefunction() in ngFor with Angular

In my Angular project, I am using an ngFor loop to iterate over keys generated by Object.keys() in the following code snippet: <ul id='nav-tablist' class='tabrows'> <li *ngFor="let tab of obj.keys(tabList)"> ...

What is the best way to deliver data from the main Vue instance to components that are being utilized by vue-router?

Currently, I am utilizing vue-router within a single HTML file instead of using separate file components. I am encountering an issue where I am unsure how to pass the data stored in the Vue data object to the component when loading it for a route. Oddly e ...

Keeping the header fixed on a sticky div (tocbot)

While working on my website, I decided to implement a Table of Contents section using tocbot. However, I encountered an issue where the Title I added above the table doesn't stay fixed when scrolling. https://i.stack.imgur.com/vCm1K.gif Here's ...

The canvas element automatically removes itself after being resized within an HTML5/JavaScript environment

I created a canvas that is interactive and responsive to screen size. However, I encountered an issue where the canvas clears itself when the browser is resized by just one pixel. Is there a way to prevent this from happening? I have included code in my sc ...

Is there a way to retrieve the filename of a file uploaded using a shiny fileInput function?

This shiny app has a feature where users land on the 'Upload data' panel upon launching. To restrict access to the other two 'tabpanels', users must first upload both necessary files in the 'Upload data' tab. The condition for ...

The functionality of jQuery's appendTo method seems to be malfunctioning

I am trying to display an image with a popup using jQuery mobile. In my loop, I have the code below: for( var i = 0; i < imageArray.length; i++ ) { counter ++; // Create a new Image element var img = $('<img data-rel="popup" class=" ...

Encountering a tsx-loader issue when integrating tsx with vuejs

I've been attempting to integrate TSX with Vuejs based on several blog posts, but I'm consistently encountering the error displayed below. I cloned a starter kit from GitHub and it worked fine, leading me to believe that there may be an issue wit ...

When a specific JavaScript function is triggered, the value of an HTML control will reset to its original default value

I have a form with a specific requirement. I need to allow users to input data in a text field and press enter, which should dynamically create new controls like another text field, a dropdown menu, and another text field using jQuery. While the functional ...

In Vue JS, ensure that each item is loaded only after the previous item has finished loading

Is there a way to optimize the loading of around 1000 static images, .gifs, and videos for an online slideshow presentation? Currently, all items are loading simultaneously causing viewers to wait to see the first item. How can each item be loaded after th ...

Mishandling of string interpretation

I'm having trouble converting ANSI color codes from console output into HTML. While I discovered a script that can handle this task, I am struggling to make it parse the strings within node js properly. Even when I attempted to JSON.stringify it to in ...

Converting an Object into an Array of Objects

The question at hand is quite simple yet lacks a definitive answer. I have an object and my objective is to take each key and value pair, transform them into objects, and then push them into an array. To illustrate this, consider the example below. { tit ...

Here's a unique version: "Steps for replacing an outdated chart with a new one using Chart.js and

Is there a way to remove an old chart when the user clicks a button to retrieve a new chart? I understand that the existing chart needs to be destroyed before a new one is generated, but currently, the code does not support destroying non-globally create ...

Display the output of JSON.stringify in a neatly formatted table

After sending my table data to the database using ajax, I am now trying to retrieve it by clicking on the open button. $.ajax({ type: "POST", url: "http://localhost/./Service/GetPageInfo", dataType: "json", ...

creating a Vuejs button function that will add together two given numbers

Help needed with VueJs code to display the sum of two numbers. Seeking assistance in developing a feature that calculates the sum only when the user clicks a button. Any guidance would be greatly appreciated! <!DOCTYPE html> <html lang="en"> ...