JavaScript: How come my closure isn't functioning properly?

In the provided code snippet, only the last value of .enter_form input is being assigned to the last

MYAPP.list[0].responses[MYAPP.score.round].form[key]
, where the variable key is the only element that changes. This issue seems to be caused by passing only the final key value to the addEntry() function, but a solution to this problem has proven elusive.

$('.enter_form input').each(function() {
    var key = $(this).attr('id');
    var val = $(this).val();
    userDict[key] = val;
    MYAPP.list[0].responses[MYAPP.score.round].form = [];
    function addEntry() {
        return function(k) {
            MYAPP.list[0].responses[MYAPP.score.round].form[k] =  {'entry': userDict[k]};
        }(key);
    }
    addEntry();
}

Answer №1

It seems that the addEntry function in your code is unnecessary as each iteration already runs within its own scope, preserving the values of key and val properly. Additionally, the array you were inserting into was being overwritten in every iteration, resulting in an array with only one value at the end of the loop. It would be more appropriate for it to be an object rather than an array, even if the ids are numerical.

// This was being overwritten in each iteration
MYAPP.list[0].responses[MYAPP.score.round].form = {};

$('.enter_form input').each(function() {

    var el= $(this); // caching instead of creating a new jQuery object each time
    var key = el.attr('id');
    var val = el.val();

    userDict[key] = val;
    MYAPP.list[0].responses[MYAPP.score.round].form[key] =  {'entry': userDict[key]};

}); // ); was also missing

This should resolve the issue.

Answer №2

Deciphering the intended purpose of this code may be a bit challenging, but here is my interpretation:

MYAPP.list[0].responses[MYAPP.score.round].form = [];
$('.enter_form input').each(function() {
    var $this = $(this),
        key = this.id,
        val = $this.val();
    userDict[key] = val;
    MYAPP.list[0].responses[MYAPP.score.round].form[key] = {
        'entry': val
    };
});

This code snippet aims to dynamically populate entries in

MYAPP.list[0].responses[MYAPP.score.round].form
based on the IDs of the form's input elements while also updating the userDict.

Based on your statement that "...key is the only thing that varies" (presumably $(this).val() varies as well), I tailored the logic accordingly. It appears that the intention is to assign values entered by users to the corresponding input IDs within the form.

On a separate note, if the ids of the input elements are not purely numeric, it might be more appropriate to initialize an empty object:

MYAPP.list[0].responses[MYAPP.score.round].form = {};
//                                                ^^-- modification made here

Instead of initializing with an empty array:

MYAPP.list[0].responses[MYAPP.score.round].form = [];

Nevertheless, even if non-numeric properties are added, using arrays will still function correctly since arrays are objects too.


Off-topic: Utilizing this.id is preferable over $(this).attr('id').

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

Error message: "Error creating tags using the Tag-It jQuery plugin"

I recently started using the tag-it jquery plugin available at https://github.com/aehlke/tag-it var ip_elem = $('#my-tags'); ip_elem.tagit({ removeConfirmation: false, caseSensitive: false, allowDuplicates: false, allowSpaces: t ...

Which core modules of Node Js serve as the foundation for Express Js?

Which core modules of Node.Js are utilized in the construction of the Express Js Framework? Besides the 'http' and 'fs' modules, what other modules does Express Js integrate? ...

Having trouble getting a Three.js invisible plane to work correctly with raycaster.intersectObject?

I've been experimenting with creating draggable objects similar to this interesting example: The array objectMoverLines contains the objects that should be draggable. To incorporate a plane into my scene, I utilized the following code: plane = new ...

Combining Node.js with Backbone.js: A Perfect Pairing

After extensive research on both Node.js and Backbone.js, including tutorials and courses from Code School, I have a solid understanding of the roles these technologies play in web applications. However, my challenge lies in integrating Node.js and Backbo ...

"Clicking on AppBar MenuItem functions properly on desktop, but it does not work on mobile devices in Material UI using

Within my reactjs application that employs Material UI, I have a Appbar containing a dropdown menu positioned in the top right corner. On desktop, the onClick function for each MenuItem works as expected. However, on mobile devices, the function does not t ...

How to decipher strings encrypted using JS crypto in Java

How can I translate this JavaScript code into Java using javax.crypto.xxx? encryptString : function encryptString(str, password) { var cipher = crypto.createCipher("aes128", password); return cipher.update(str, "binary", "base64") + ...

The component in React does not refresh after updating the state

I have a React page where I am displaying a list of quizzes fetched from an external API. There's also a "New Quiz" button that opens a dialog with a form for users to create a new quiz. My issue is with making the table re-render once the POST reque ...

Encountering difficulties in fetching data with formData in nextJS

Exploring the realm of NextJS and delving into server side actions. I'm facing a challenge with this specific request. import { revalidatePath } from "next/cache"; export async function submitIPCR(prevState: any, formData: FormData) { / ...

Using Laravel, how can I retrieve the specific user ID associated with an element?

I am seeking a solution to retrieve the User ID from the users table using either JavaScript or Laravel. But why do I need it? The reason is that I want to populate a modal window popup with specific user information. I currently have 10 users, each with ...

How can I create an HTML select dropdown menu with a maximum height of 100% and a dynamic size?

The dropdown menu I created using an HTML select tag contains a total of 152 options. However, the large number of options causes some of them to be out of view on most monitors when the size is set to 152. I attempted to limit the number of displayed opti ...

Error encountered: Unexpected token found while trying to import react-native-fetch-blob

We are facing an issue while trying to incorporate the react-native-fetch-blob package into our project using the code snippet below: const RNFetchBlob = require('react-native-fetch-blob'); const firebase = require('firebase'); Howeve ...

How can I send a jQuery ajax request with multiple custom headers?

I am facing an issue with my basic ajax request as I am trying to include a custom header using the following code: _auth=1,[my_apikey], Interestingly, when I make the same request using Postman, I receive a valid JSON response. However, when I attempt t ...

Complete the form to receive the redirection link

For the purpose of registering a server on a website, I am required to input data. This involves filling out a form on the initial webpage and upon submission, being directed to a dynamically generated page where further information must be entered. It is ...

Sending multiple values with the same name via AJAX using PHP

I'm facing an issue with my code: <form method="post" id="result-image" name="result-image" action="" > <?php $i=1; foreach ($data as $key => $datas) { ?> <div class="col-md-2 thumb custom-size col-lg-3 col-xs-4"> ...

Anticipated spatial glitch problem involving the gadicc/meteor-reactive-window package for Meteor

Utilizing the gadicc/meteor-reactive-window Meteor Package to switch templates based on screen size. This file is named pictureDisplatSection.html <template name="pictureDisplaySection"> <div class="display"> ...

Displaying a loading spinner while waiting for the Vue.js app to render

Currently, I am developing a Vue.js application and I'm facing a challenge in adding a loading spinner before the app component is rendered. Instagram has a similar feature where they display their logo before showing the page contents. I have tried v ...

What is the process for setting up a single button selection using OR logic and multiple button selection using AND logic?

Currently working on implementing button functionality in React for filtering data. The requirement is that when selecting specific criteria, such as bedroom 3 or multiple selections like bedroom 2 and 3, the logic should vary. For instance, selecting bedr ...

Show a decimal value as an integer in Razor

Looking for assistance with razor code: @Html.DisplayFor(model => item.sepordan_melk_foroshes.ghamat_total) The current output is: 123.00 How can I remove the decimal and display it like this?: 123 Any help with this would be greatly appreciated. ...

No content appearing instead of AngularJS code displayed

My goal is to retrieve data from a MySQL database using PHP and then pass that data in JSON format to AngularJS for display in a table. The HTML code looks like this: <body ng-app="myModule"> <div class="row"> <div class="col-lg-12 ...

Guide on obtaining an obscure style guideline in MS Edge using JavaScript

If you are looking to utilize the object-fit CSS rule, keep in mind that it is not supported in MSIE and MS Edge Browsers. While there are polyfills available for IE, none of them seem to work in Edge from my experience. For instance, the polyfill fitie b ...