title: Event handlers inside a Javascript loop - need a closure?
body: <p>I'm working with a bit of html and Javascript code that I've taken over from someone else. The page reloads a table of data (via an asynchronous request) every ten seconds, and then re-builds the table using some DOM code. The code in question looks something like this:</p>
  
  <pre><code>var blah = xmlres.getElementsByTagName('blah');
  for(var i = 0; i &lt; blah.length; i++) {
      var td = document.createElement('td');
      var select = document.createElement('select');
      select.setAttribute("...", "...");
      select.onchange = function() {
          onStatusChanged(select, callid, anotherid);
      };
      td.appendChild(select);
  }
  </code></pre>
  
  <p>When the <code>onchange</code> event is fired for a <code>&lt;select&gt;</code> element however, it seems like the same values are being passed to the <code>onStatusChanged()</code> method for every <code>&lt;select&gt;</code> in the table (I've verified that in each iteration of the loop, <code>callid</code> and <code>anotherid</code> are being given new, distinct values). </p>
  
  <p>I suspect this is occuring because of the nature of how I am setting the event handler, with the <code>select.onchange = function()</code> syntax. If I understand how this is working correctly, this syntax sets a closure for the onchange event to be a function which refers to these two references, which end up having a final value of whatever they are set to on the last iteration of the loop. When the event fires, the value referenced by <code>callid</code> and <code>anotherid</code> is the value set in the last iteration, not the value set at the individual iteration.</p>
  
  <p>Is there a way that I can copy the value of the parameters I am passing to <code>onStatusChanged()</code>?</p>
  
  <p><em>I've changed the title to better reflect the question and the accepted answer.</em></p>