title: Jquery sortable on dynamically created divs
body: <p>I have a rails 4 app that has nested fields and I'm trying to get jQuery sortable working on products.</p>
  
  <p>Here is my code:</p>
  
  <pre><code>&lt;div class="form-group" id='products'&gt;
     &lt;%= f.fields_for :products do |builder| %&gt;
        &lt;%= render 'product_fields', f: builder %&gt;
     &lt;% end %&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>and my product_fields partial looks like:</p>
  
  <pre><code>&lt;div class='product'&gt;
     test
  &lt;/div&gt;
  </code></pre>
  
  <p>and my jQuery looks like:</p>
  
  <pre><code>$('#products').sortable({
     items: ".product"
  });
  $('form').on('click', '.add_fields', function(e) {
     var regexp, time;
     time = new Date().getTime();
     regexp = new RegExp($(this).data('id'), 'g');
     $(this).before($(this).data('fields').replace(regexp, time));
  
     return e.preventDefault();
  });
  </code></pre>
  
  <p>Basically, what's happening is that I already have one <code>.product</code> on the page, when it is loaded (via Rails). Then when you click a button I have some jQuery that generates identical <code>.product</code> divs. But only the first <code>.product</code> (the one that is created by Rails server-side) is the only one that is sortable.</p>