developing a function within a loop using an index

To create an object in a for loop and add a click function that calls another function while passing the index of the clicked object, you can use the following loop:

var markers = [];
for (x = 0; x < response.data.length; x++) {
    var ret = {
        onClicked: function (index) { 
            return function() { onMarkerClicked(index); };
        }(x),
        locationId: response.data[x].CASO_nid,
        id: x,
        latitude: response.data[x].Latitude,
        longitude: response.data[x].Longitude,
        title: x,
        showWindow: false,
        fit: true
    };
    markers.push(ret);
}
$scope.results = markers;

Upon inspecting the objects created in console, it is observed that all references to 'x' are correctly assigned except within the click function where it remains as just 'x'. This results in all objects referencing the last value of 'x'. To address this issue, you can modify the function logic as shown above to ensure each object holds its respective index value upon being clicked.

See in console:

0:  
Objectfit: true
id: 0 
idKey: 0 
latitude: 42.0230636
locationId:10299 
longitude: -87.9620276
onClicked: function () { onMarkerClicked(x); }
showWindow: false
title: 0

Answer №1

Consider creating closures for every loop:

for (count = 0; count < response.data.length; count++) {
     (function(y) {
            var result = {
                onClicked: function () { onMarkerClicked(y); },
                locationId: response.data[y].CASO_nid,
                id: y,  //-displays correct index
                latitude: response.data[y].Latitude,
                longitude: response.data[y].Longitude,
                title: y,  // displays correct index
                showWindow: false,
                fit: true
            };
            markers.push(result);
      }(count))
 }

Alternatively, you can use forEach which also establishes closures.

response.data.forEach(function (val, y){
    var result = {
                onClicked: function () { onMarkerClicked(y); },
                locationId: val.CASO_nid,
                id: y,  //-displays correct index
                latitude: val.Latitude,
                longitude: val.Longitude,
                title: y,  // displays correct index
                showWindow: false,
                fit: true
            };
        markers.push(result);
});

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

Able to display the value when printing it out, however when trying to set it in setState, it becomes

Within my form, there's a function that receives the value: _onChange(ev, option) { console.log(option.key) // Value of option key is 3 this.setState({ dropdownValue:option.key }) // Attempting to set state with 'undefined' as ...

TroubControls not functioning properly in ThreeJS when using import map

Looking for assistance in setting up a simple ThreeJs with OrbitControls for pan and zoom. I successfully got it working with an older version (128), but encountering issues with the newer r168. In my example, I am attempting to directly embed the JavaScr ...

The anticipated reply was supposed to consist of an array, however it ended up being an

I'm brand new to Angular and I've been searching for a solution to my issue with no luck. My app is supposed to retrieve data from a MongoDB database and display it to the user. However, I keep getting this error message: Error: [$resource:bad ...

Looking to dynamically generate HTML tags using jQuery and JSON?

Looking for help with inserting HTML code into a div using jQuery. <div id="addme"></div> Here is some HTML with PHP: <div class="col-md-4 product secondproduct"> <div class="images1"> <a href="<?php echo base_u ...

Events are not being emitted by Socket.io

I recently started learning about socket.io and began following a tutorial on the socket.io website. I have installed everything correctly, but it seems that the socket is unable to emit the event in the index.html file. Can anyone help me with this? Here ...

What could be causing my dangerouslySetInnerHTML to show altered content?

I am working on a project using React and have encountered an issue with the code: const externalMarkup = ` <a data-refpt='DN_0OKF_177480_ID0EMPAC' /> <ol> <li value='1'> <p> <strong&g ...

Troubleshooting IE Freezing Issue Due to JavaScript Code with .addClass and .removeClass

Need some help troubleshooting why my code is causing IE to crash. After commenting out sections, I discovered that the issue arises when using .addClass and/or .removeClass inside the if conditions: if ( percentExpenses > 50 && percentExpenses ...

The image momentarily pauses as the arrow keys are switched

I have a query regarding the movement of the main player image. While it generally moves smoothly Left or Right, there is an issue when quickly switching directions from right to left. When the left key is pressed while the right key is still held down, th ...

Utilizing the .fadeToggle() function to create a fading effect for text, which fades in and out

I am on the verge of achieving my goal, but I could use a little more assistance with this. $('.change').hover(function() { $(this).fadeToggle('slow', 'linear', function() { $(this).text('wanna be CodeNinja' ...

Guide on combining two assertion statements using an OR condition in Cypress

Being new to the world of UI automation/Cypress, I am seeking assistance in setting up assertions on a JavaScript object returned by the cypress-ag-grid package. The code I have is reading data from an ag-grid. cy.get("#myGrid").getAgGridData(). ...

Maximum character count for text input in node.js/express

I am trying to save a base64-encoded image string in my Postgres database using node.js/express. However, I am facing an issue with fetching the string. Is there a limitation on the size of data that can be stored? Before making an AJAX call from the fron ...

Which is better for testing in Cypress: classes or functions?

When it comes to testing in Cypress, which approach do you believe is more efficient? Functions: 'support/pages/login.js' export const login = (username, password) => { cy.get('#username').type(username); cy.get(& ...

Lock the initial column in an HTML table

Hey there! I've been trying to freeze the first column of my HTML table, and while I managed to do so after a few attempts, I encountered an issue. When I scroll the table horizontally, the columns on the left seem to overlap with the first column, an ...

JQuery submit event not triggering object setting

I'm looking to gather input values from a form and store them in an object for an offer. After trying the following code on submit: $(document).ready(function(){ $('#formOffre').on('submit', function(e) { e.preventDefault ...

Toggle visibility of input field in HTML form

Is there a way to make the second password input only visible once the user starts typing in the first input? Additionally, can both inputs be required or none at all? <form name="signUpForm"> ... <input ng-modal="password" type="passw ...

The texture appears blurred in the three.js viewport and lacks clarity

I have loaded a shirt object with texture, set Ambient light and directional light, but the render part does not show clearly. Can someone help me figure out how to set the light effect? Here is my code: var container; var camera, scene, renderer; var mou ...

Configuring a Themeforest HTML template with Vue and Laravel. Issue encountered when attempting to load JS files using router.push

Currently working on my first frontend website using Vue and Laravel. I decided to purchase a template from Themeforest which is based on HTML/CSS/JavaScript. The setup of Vue and Vue Router with Laravel is complete and everything seems to be functioning ...

The latest error in the Next.js 13 app directory: React child is not valid (detected: [object Promise])

I am currently utilizing the new app directory feature in Next.js 13. Within my project, I have a page component located at app/page.tsx. This component contains the following code snippet: "use client"; import { useState } from "react" ...

Troubleshooting drag-and-drop functionality in a JavaScript HTML5 application resembling a Gmail upload interface

Here is a snapshot of my user interface: Each node in the tree structure is represented by an <li> element along with an <a> link. Furthermore, each folder serves as a dropzone for file uploads similar to the drag-and-drop feature found in Gm ...

Encoding a single key-value pair in JSON format with PHP: a simple guide

I attempted running this code, but encountered an error. $queryfetch = 'select * from table'; $result = mysqli_query($connection, $queryfetch); $row = mysqli_fetch_assoc($result); $data = []; foreach($row as $key) { $dat ...