Set a parameter value for the onclick event when dynamically generating an input element

Utilizing a JSON object, I am generating a table with associated values and including a remove button for each entry:

for (var keyValue in thisAdminResult) {
    if (thisAdminResult.hasOwnProperty(keyValue)) {

        var row = document.createElement('tr');
        var firstColumn = document.createElement('td');
        var secondColumn = document.createElement('td');
        var thirdColumn = document.createElement('td');
        var fourthColumn = document.createElement('td');

        var password = document.createElement('input');
        password.type = "password";

        var removeButton = document.createElement('input');
        removeButton.type = "button";

        var updateButton = document.createElement('input');
        updateButton.type = "button";

        firstColumn.appendChild(document.createTextNode(keyValue));

        password.value = thisAdminResult[keyValue];

        secondColumn.appendChild(password);
        removeButton.value = 'remove';

        removeButton.onclick = function () {
            remove(keyValue);
        }

        thirdColumn.appendChild(removeButton);

        updateButton.value = 'update'
        updateButton.onclick = function () {
            //update(keyValue);
        }

        fourthColumn.appendChild(updateButton);

        row.appendChild(firstColumn);
        row.appendChild(secondColumn);
        row.appendChild(thirdColumn);
        row.appendChild(fourthColumn);

        table.appendChild(row);
    }
}

The issue I'm facing is that when I click on any remove button, it always triggers the remove function with the same argument value (the last value of the 'keyValue' variable).

If anyone knows how to fix this problem, please advise.

Answer №1

An effective way to utilize an IIFE is by creating a function that captures the current value of keyValue and returns it. Here's an example:

submitButton.onclick = (function (input) {
    return function(){ 
        submit(input); 
    };
})(userInput);

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

Using jQuery to extract the value of an object from an <li> element and updating the class attribute of the <li> element

There is a div element: <div id="ddDistr" class="searchBoxSortDistrict" tabindex="1"> <ul id="ddd"> </ul> </div> I have inserted HTML from json into it: $("#ddd").html(" "), $.each(dis, function( index, value) { $("#dd ...

The UI-Grid feature in Angular, when set to right-to-left (RTL) mode, incorrectly displays data in the opposite order compared to the

In my _Layout.cshtml file, I have a CSS that sets all UI controls to right-to-left direction using the following code: * { direction: rtl; } Currently, I am working with Angular's UI-Grid, and in RTL Localization, the ...

Toggle the visibility of a div depending on a value that is loaded on the page

I need help with a functionality that will hide or show the following div based on the value of <%= ItemCount%>. If the number is less than five, I want the div to be hidden. On the other hand, if it is above 5, then the div should be visible. Any ...

Guide on adding data into a database through URL parameters using the CodeIgniter framework

Currently, I am utilizing CodeIgniter to retrieve JSON items from a database and insert them. Initially, I followed the tutorial on the CodeIgniter website which involved using a form to send data to the database, and everything functioned correctly. Howev ...

Using Three.JS 'OrbitControls' in VueJS application results in a black screen appearing?

Currently, I've been delving into the basic cube exercise on Three.js, and incorporating the three.js cube into my Vue.JS application. Initially, everything was functioning smoothly, with my cube rotating as intended using animate, etc. However, thi ...

unable to convert PDO query result into JSON format

I am having trouble with the json_encode function when trying to encode an array returned from PDO: When I run var_dump(json_encode($result));, it shows false To troubleshoot, I have tried reassigning this array by looping through the results obtained fr ...

Is there a way to transfer a JSON map object from Flask and then utilize it as a JavaScript object?

python server code from flask import Flask, render_template, request import os import sys import json data_raw = [('0', '1', '0', '0'), ('0', '0', '1', '0'), ('1', ...

Instantly magnifying on the initial point regardless of the zoom type chosen is a feature of Chart.js zoom

Despite adding zoom functionality to my line chart, I am facing an issue where it automatically zooms in to the first point and does not allow me to zoom back out, except for using the reset zoom function. The zoom out function is also not working properly ...

Stop Users from Inputting Decimal Numbers with JavaScript

Just starting out with Java Script and looking to restrict users from entering decimals in a field using JavaScript. I attempted this approach but encountered the following error. Syntax error on token "_$tag____________", invalid AssignmentOperator < ...

Transfer the data in the columns of Sheet1 to Sheet2 and eliminate any duplicates using Google App Script

Is there a way to transfer only unique rows from a SOURCE Spreadsheet to a DESTINATION spreadsheet? Spreadsheet #1 (SOURCE) - This sheet contains ID's and Names, but has duplicate rows. There are over 500k rows in this sheet and it is view-only. Spre ...

Several validation checks - logic malfunction

I have implemented a validation feature for passwords on a form, but I suspect there may be a logic error in my code that I haven't caught yet (blame it on the coffee machine!). Take a look at the JavaScript below: <script type="text/javascript"& ...

React - modifying parent's Redux property

After connecting my Container to redux using the following: const mapStateToProps = ({ MyReducer }) => ({ myProp: MyReducer.myProp }); I am wondering if it is possible to manually set the value of myProp from the parent component (bypassing redux) ...

Combining Gridstack.js with Vue 3 components

I'm currently working on setting up a gridstack.js dashboard using Vue 3 and I am looking to have the grid stack items incorporate dynamic vue 3 components. The issue arises where these grid stack items can only accept HTML content. Even though the d ...

What is the most efficient way to loop through nested JSON using jQuery in one go?

I have a substantial JSON file containing a snippet of the data shown below. The values used in the snippet are placeholders for this specific query. "restaurants":[ "name": "Burger King", "location": "Seattle, WA", "la ...

The font-face feature seems to be malfunctioning across all browsers

I'm encountering difficulties with rendering fonts on my react application. I'm unsure of what I might be doing incorrectly. I have implemented font-face in my project and here is a snippet from my font.styl file. All the fonts are located in th ...

Is there a way to identify the presence of a mouse on a website?

In the process of developing a website, I encountered a dilemma with navigation buttons. They needed to be large for aesthetic reasons and ease of use but had to be small when not in use. To address this, I decided to shrink the buttons into thumbnails on ...

Looping through files in batches to combine them for the purpose of mongoimport in Bash

I am facing a challenge with a directory containing 2.5 million small JSON files, totaling 104gb on disk. These multi-line files need to be transformed into JSON arrays for efficient import using mongoimport. Each resulting file must not exceed 16mb in siz ...

What is the best location for me to update the state in order to ensure that I receive the accurate information from

Currently working on a major project to showcase my development skills in an upcoming job interview, I find myself a) lacking experience and b) short on time to make any significant code changes (like implementing Hooks). The task at hand involves retriev ...

Implementing a watcher property in JavaScript to dynamically add a class to an element

I'm currently facing an issue where I need to apply a class to an element when a certain data property changes. My approach involves using a watcher to monitor the value change and adding a class through JavaScript, as demonstrated in the code snippet ...

Why is it not possible to declare an interface or type within a TypeScript class?

I am struggling to define interface | type within a TypeScript class. Here is the code snippet: class MyClass { interface IClass { name: string, id: string } } However, I keep encountering this error: Unexpected token. A constructo ...