title: Why is the loop assigning a reference of the last index element to?
body: <p>I want to add an event listener to all of my  tags, <em>each passing a reference to itself</em> as a parameter when the even is triggered. Here is the function I wrote:</p>
  
  <pre><code>function validateDigitsFeature()
  {
      //  Add the event listeners to input tags
      //      Get the array of input tags
      var inputTags = document.getElementsByClassName('validateInput');
      var tagId;
      //      Loop through them, adding the onkeypress event listener to each one
      for (var i = 0; i &lt; inputTags.length; i++)
      {
          //  Give each input element an id
          tagId = inputTags[i].id = 'input_id_' + i;
          inputTags[i].addEventListener('keyup', function(){isNumberOrDot(event, tagId);}, false);
      }
  }
  </code></pre>
  
  <p>Basically the function should do the following:</p>
  
  <ol>
  <li>Store all the input tags with the specified classname in an array</li>
  <li>Loop through the array, adding an id to each tag and</li>
  <li>Adding the <code>onkeyup</code> event listener with the <code>isNumberOrDot(event, tagId)</code> handler.</li>
  </ol>
  
  <h2>Problem</h2>
  
  <p>The onkeyup event is added, but they handlers of each one is <strong>always</strong> referencing the <code>tagId</code>of the last element of the array.</p>
  
  <h2>Question</h2>
  
  <p>What is wrong with the code/logic? And how can it be fixed?</p>
  
  <h2>Note</h2>
  
  <p>Sure this problem is related to JavaScript Closure in loops, while this question could have a more general answer, it is specific to event listeners being used. To more advanced developers, it might be easy to apply the general solution to this problem. But to me the other solutions still didn't provide a full explanation or even worked.</p>
  
  <p>Thank you in advance.</p>