skip to Main Content

I am creating inputs in a table via a loop.
First I create a new cell

var nestedCell = newRow.insertCell(columncounter);

Then I create a new input, each input has a unique ID.

let input = document.createElement('input');
input.type = 'text';
input.id = thisInputID;
input.value = value;

Then I try to insert an "onchange" function to that input

input.onchange =  function() { 
   alert(thisInputID);
}

The onchange function is fired, but because the value of thisInputID changes on every iteration only the last "thisInputID " is displayed instead of the id for that particular input. This is a problem. How do I assign an onchange function to each input which will pass a unique identifier for that input?

Here is the code all in one block:

                        var nestedCell = newRow.insertCell(columncounter);

                        let input = document.createElement('input');
                        input.type = 'text';
                        input.id = thisInputID;
                        input.value = value;
                        input.onchange =  function() { 
                            alert(thisInputID);
                        }

                        nestedCell.appendChild(input);

Edit: You have already given me a working answer 🙂 but here is a jsfiddle showing the issue https://jsfiddle.net/carlschwarz/2bw1dm8k/1/

2

Answers


  1. If it just needs to alert its own id then you can access that directly:

    input.onchange = function() { 
      alert(this.id);
    }
    
    Login or Signup to reply.
  2. variables inside for loops declared with var have function scope. You can use block level scoped declerations, const/let, listen to others as they pointed out the solution, or do this ugly thing that traps the variable:

    input.onchange =  ((id) => function() { 
      alert(id);
    })(thisInputID)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search