Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8031785
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 5, 20262026-06-05T01:12:45+00:00 2026-06-05T01:12:45+00:00

I’m using the nested form gem in my Rails 3 app: https://github.com/ryanb/nested_form . I’m

  • 0

I’m using the nested form gem in my Rails 3 app: https://github.com/ryanb/nested_form. I’m able to add/remove the “audience fields” in my form. The audience model belongs to the upload model.

What I’d like to be able to do is to count the number of times the audience fields are added in the form. So, for example, the form will initially display “Audience 1” above the audience fields. If I add another audience field, then “Audience 2” will be displayed, and so on.

application.js

var n = $("div.audiencefields").length;
  $("span").text("Audience " + n);

What am I doing wrong?

edit:

application.js

  $("#removelink").hide().filter(":first-child").show();

  $("div.audiencefields span").each(function(index, element) {
  $(this).text("Audience " + (index + 1));});

nested_form.js

jQuery(function($) {
window.NestedFormEvents = function() {
this.addFields = $.proxy(this.addFields, this);
this.removeFields = $.proxy(this.removeFields, this);
};

NestedFormEvents.prototype = {
addFields: function(e) {
  // Setup
  var link    = e.currentTarget;
  var assoc   = $(link).attr('data-association');            // Name of child
  var content = $('#' + assoc + '_fields_blueprint').html(); // Fields template

  // Make the context correct by replacing new_<parents> with the generated ID
  // of each of the parent objects
  var context = ($(link).closest('.fields').closestChild('input:first').attr('name') || '').replace(new RegExp('\[[a-z]+\]$'), '');


  // context will be something like this for a brand new form:
  // project[tasks_attributes][new_1255929127459][assignments_attributes][new_1255929128105]
  // or for an edit form:
  // project[tasks_attributes][0][assignments_attributes][1]
  if (context) {
    var parentNames = context.match(/[a-z_]+_attributes/g) || [];
    var parentIds   = context.match(/(new_)?[0-9]+/g) || [];

    for(var i = 0; i < parentNames.length; i++) {
      if(parentIds[i]) {
        content = content.replace(
          new RegExp('(_' + parentNames[i] + ')_.+?_', 'g'),
          '$1_' + parentIds[i] + '_');

        content = content.replace(
          new RegExp('(\\[' + parentNames[i] + '\\])\\[.+?\\]', 'g'),
          '$1[' + parentIds[i] + ']');
      }
    }
  }

  // Make a unique ID for the new child
  var regexp  = new RegExp('new_' + assoc, 'g');
  var new_id  = new Date().getTime();
  content     = content.replace(regexp, "new_" + new_id);

  var field = this.insertFields(content, assoc, link);
  $(link).closest("form")
    .trigger({ type: 'nested:fieldAdded', field: field })
    .trigger({ type: 'nested:fieldAdded:' + assoc, field: field });
  return false;
},
insertFields: function(content, assoc, link) {
  return $(content).insertBefore(link);
},
removeFields: function(e) {
  var link = e.currentTarget;
  var hiddenField = $(link).prev('input[type=hidden]');
  hiddenField.val('1');
  // if (hiddenField) {
  //   $(link).v
  //   hiddenField.value = '1';
  // }
  var field = $(link).closest('.fields');
  field.hide();
  $(link).closest("form").trigger({ type: 'nested:fieldRemoved', field: field });
  return false;
}
};

  window.nestedFormEvents = new NestedFormEvents();
$('form a.add_nested_fields').live('click', nestedFormEvents.addFields);
$('form a.remove_nested_fields').live('click', nestedFormEvents.removeFields);
});


// http://plugins.jquery.com/project/closestChild
/*
* Copyright 2011, Tobias Lindig
*
* Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
* and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
*
*/
(function($) {
$.fn.closestChild = function(selector) {
// breadth first search for the first matched node
if (selector && selector != '') {
  var queue = [];
  queue.push(this);
  while(queue.length > 0) {
    var node = queue.shift();
    var children = node.children();
    for(var i = 0; i < children.length; ++i) {
      var child = $(children[i]);
      if (child.is(selector)) {
        return child; //well, we found one
      }
      queue.push(child);
    }
  }
}
return $();//nothing found
};
   })(jQuery);

new.html.erb

  <%= f.fields_for :audiences do |audience_form| %>
  <div class="audiencefields">
  <span></span>
  <p>   
    <%= audience_form.label :number_of_people %><br />
    <%= audience_form.text_field :number_of_people %>
  </p>
  <p>
    <%= audience_form.label :gender %><br />
    <%= audience_form.text_field :gender %>
  </p>
  <p>
    <%= audience_form.label :ethnicity %><br />
    <%= audience_form.text_field :ethnicity %>
  </p>
  <p>
    <%= audience_form.label :age %><br />
    <%= audience_form.text_field :age %>
  </p>
  </div>

  <%= audience_form.link_to_remove "Remove this", :id => "removelink" %>
  <% end %>

  <p><%= f.link_to_add "Add this", :audiences, :id => "addlink" %></p>
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-05T01:12:47+00:00Added an answer on June 5, 2026 at 1:12 am

    I create another answer as comments don’t allow formatting code

    If that is the file you are using then there on lines 69-71 you can find the following code

    window.nestedFormEvents = new NestedFormEvents();
    $('form a.add_nested_fields').live('click', nestedFormEvents.addFields);
    $('form a.remove_nested_fields').live('click', nestedFormEvents.removeFields);
    

    This bind click events to the add and remove links. In your custom script bind events in the same way. It will be executed once the above is completed. So your code should like this

    $('form a.add_nested_fields, form a.remove_nested_fields').live('click', function(){
    
        $("div.audiencefields span").each(function(index, element) {
            //index starts with 0
            $(this).text("Audience " + (index + 1));
        });
    
    });
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

We're building an app, our first using Rails 3, and we're having to build
I am using Paperclip to handle profile photo uploads in my app. They upload
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
That's pretty much it. I'm using Nokogiri to scrape a web page what has
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I am reading a book about Javascript and jQuery and using one of the
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I'm using v2.0 of ClassTextile.php, with the following call: $testimonial_text = $textile->TextileRestricted($_POST['testimonial']); ... and
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
We are using XSLT to translate a RIXML file to XML. Our RIXML contains

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.