title: jQuery dynamic form adding widgets
body: <p>I am trying to make a simple UI for a MongoDB aggregation query builder. Basically a user needs to click on a dropdown option (Group By, Sort, Limit, etc) then another field should popup next to it to select the variable.</p>
  
  <p>The problem is that the field is displaying multiple times after the first drop down is selected.</p>
  
  <p>[Group By][New Field][New Field][New Field]</p>
  
  <p>The [New Field] is appearing multiple times, and I can't figure out why.</p>
  
  <pre><code>$(document).ready(function() {
  
  aggStageDropDown = function(counter) {
      return "&lt;select id='aggStage'" + counter + "'&gt;\
          &lt;option value='unselected'&gt;(Select One)&lt;/option&gt;\
          &lt;option value='group'&gt;Group&lt;/option&gt;\
          &lt;option value='match'&gt;Match&lt;/option&gt;\
          &lt;option value='unwind'&gt;Unwind&lt;/option&gt;\
          &lt;option value='sort'&gt;Sort&lt;/option&gt;\
      &lt;/select&gt;\
      "; 
  
  }
  
  varDropDown = function(counter) {
      return "&lt;select&gt;\
          &lt;option value='var1'&gt;var1&lt;/option&gt;\
          &lt;option value='var2'&gt;var2&lt;/option&gt;\
          &lt;option value='var3'&gt;var3&lt;/option&gt;\
      &lt;/select&gt;\
      ";
  }
  
  // First elements in HTML
  $("body").append("&lt;div class='container'&gt;&lt;/div&gt;")
  $(".container").append("&lt;button class='addGroup'&gt;Add More Fields&lt;/button&gt;");
  
  var counter = 1;
  
  $(".addGroup").click(function() {
  
      // Add a &lt;div&gt;, this will contain each group of form elements.
      $(".container").append(function(){
          return "&lt;div class='controlGroup' id='aggStage" + counter + "'&gt;&lt;/div&gt;";
      });
  
      // For each .controlGroup, add removeControlGroup button and add drop-down menu.
      $("#aggStage" + counter).html(function(counter){
          return "&lt;button class='removeControlGroup'&gt;X&lt;/button&gt; " + aggStageDropDown(counter);
      });
  
      counter = counter + 1;
  
      // Function to delete control group.
      $(".removeControlGroup").click(function() {
          $(this).closest("div").remove();
      });
  
      // add drop down next to control
      $("select").change(function() {
          $(this).parent().append(varDropDown); 
  
          console.log($(this).parent());
      });
  });
  </code></pre>
  
  <p>});</p>