title: Dynamically generated Select-Elements and a JavaScript Closure
body: <p>I want to generate some <code>&lt;select</code> elements dynamically. I'm copying an existing one and only change the name and the onchange-Event. This is where my problem is: Every <code>&lt;select&gt;</code> has its own ID. When the onChange-Event fires it should respond the Value and the ID of the Element. I don't know how to define the JavaScript Closure exactly. I tried it with "this.value", but apparently this does not work...
  I already found <a href="https://stackoverflow.com/questions/341723/event-handlers-inside-a-javascript-loop-need-a-closure">this</a> example, but it did not work for me at all :/</p>
  
  <p>The JavaScript:</p>
  
  <pre><code>var i = 0;
  var selectArray = [];
  
  function addSelector(){
  
  var container = document.getElementById("check0");
  
  selectArray[i] = document.getElementsByName("select0")[0].cloneNode(true);
  selectArray[i].name = 'select'+i;
  selectArray[i].onchange = function(v, i) {
          return function() {
             changeType(v, i)
          }
      }(this.value, i);
  
  container.appendChild(selectArray[i]);
  }
  
  function changeType(selected, i) {
      switch (selected) {
          case 'One':
             alert(selected+' , '+i);
              break;
          case 'Two':
              alert(selected+' , '+i);
              break;          
          case 'Three':
              alert(selected+' , '+i);
              break;
          case 'Four':
              alert(selected+' , '+i);
              break;
          case 'Five':
              alert(selected+' , '+i);
              break;
      }
  }
  </code></pre>
  
  <p>(I tried to post the HTML aswell, but for some reason i wasnt able to do this ;) )</p>
  
  <p><a href="http://jsfiddle.net/vogti/FNFQU/" rel="nofollow noreferrer">Here is the fiddle</a></p>