0

I have a JSON object and I create a table with those values and also add a remove button as below

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);
    }
}

what I need to get done is to call remove function with particular value of 'keyValue' variable, when each remove button is pressed.

But with above code

when I click any of remove button, it calls remove function with same argument value(last value of 'keyValue').

Can someone tell me what I have to do this get corrected.

bula
  • 8,719
  • 5
  • 27
  • 44
  • Related: http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example – Larry Lee Oct 25 '14 at 17:09
  • This question gets asked daily. Please take the time to search. Googling "javascript event handler in a loop" would have given you all the info you needed. –  Oct 25 '14 at 17:11
  • 1
    Your accepted answer doesn't explain much of anything, so to understand the issue, JavaScript does not have block scope. Only function scope. This means that if you need to retain the value of a variable in a loop for later access, you need to invoke a function and give it the value you want. This creates a new variable scope, so if you create your event handler there, you're now creating a new function that shares the scope with the value you passed it. Using an IIFE is a very ugly way to do this, but it works. –  Oct 25 '14 at 17:24

1 Answers1

2

You can use an IIFE to return a function with the current value of keyValue, something like

removeButton.onclick = (function (value) {
    return function(){ 
        remove(value); 
    };
})(keyValue);
Musa
  • 96,336
  • 17
  • 118
  • 137