title: Rails 3.1: Adding & Removng fields with dynamically jQuery (Railscasts #197)
body: <p>Rails noob here.<br>
  I've been searching on Google and StackOverflow for information in order to get the example used in <a href="http://railscasts.com/episodes/197-nested-model-form-part-2" rel="nofollow">Railscasts #197</a> to work but none of the links i've visited work with Rails 3.1! <br>
  When I click on the remove or add new fields button absolutely nothing happens. This is so frustrating :/</p>
  
  <p>Anyone know why the code I've provided below isn't adding fields or removing fields dynamically like in the RailsCasts episode?
  <br><br></p>
  
  <p><strong>application_helper.rb</strong></p>
  
  <pre><code>def link_to_remove_fields(name, f)
  f.hidden_field(:_destroy) + link_to_function(name, "remove_fields(this)")
  end 
  
  def link_to_add_fields(name, f, association)
  new_object = f.object.class.reflect_on_association(association).klass.new
  fields = f.fields_for(association, new_object, :child_index =&gt; "new_#{association}") do    |builder|
      render(association.to_s.singularize + "_fields", :f =&gt; builder)
   end 
      link_to_function(name, "add_fields(this, '#{association}', '#    {escape_javascript(fields)}')", :remote =&gt; true)
   end
  </code></pre>
  
  <p><br><br>
  <strong>app.js</strong></p>
  
  <pre><code>// delete characters on users#edit and users#new
  function remove_fields(link) {
  $(link).prev("input[type=hidden]").val("1");
  $(link).closest("#character").hide();
  }
  
  // add character fields on users#edit and users#new
  function add_fields(link, association, content) {  
      var new_id = new Date().getTime();  
      var regexp = new RegExp("new_" + association, "g");  
      $(link).parent().before(content.replace(regexp, new_id));  
  }
  </code></pre>
  
  <p><br><br>
  <strong>html</strong></p>
  
  <pre><code>&lt;div id="account"&gt;
  &lt;div class="field"&gt;
      &lt;%= f.label :account_name %&gt;&lt;br /&gt;
      &lt;%= f.text_field :account_name %&gt;
  &lt;/div&gt;
  &lt;div class="field"&gt;
      &lt;%= f.radio_button(:realm, "USWest") %&gt;
      &lt;%= f.label(:realm, "USWest") %&gt;
  
      &lt;%= f.radio_button(:realm, "USEast") %&gt;
      &lt;%= f.label(:realm, "USEast") %&gt;
  
      &lt;%= f.radio_button(:realm, "Europe") %&gt;
      &lt;%= f.label(:realm, "Europe") %&gt;
  
      &lt;%= f.radio_button(:realm, "Asia") %&gt;
      &lt;%= f.label(:realm, "Asia") %&gt;
  &lt;/div&gt;      
  &lt;div class="field"&gt;
      &lt;%= link_to_add_fields "Add new account", f, :characters %&gt;
  &lt;/div&gt;
  
  &lt;div class="field"&gt; 
      &lt;%= f.hidden_field :_destroy %&gt;
       &lt;%= link_to_remove_fields "remove", f %&gt;
  &lt;/div&gt;
  &lt;%= f.fields_for :characters do |builder| %&gt;
  &lt;%= render "characters/char_fields", :f =&gt; builder %&gt;
  &lt;% end %&gt;
  &lt;/div&gt;
  </code></pre>