I have this select in Rails

<%= g.select :num_periods, options_for_select([["Mensual", 12], ["Semestral", 6], ["Trimestral", 4], ["Anual", 1]]) %>

Depending on the selected option I want to display n times this nested form. (I'm displaying it with a loop now)

<% for i in (1..4) %>
  <%= g.fields_for :periods do |p| %>
    <%= p.label "Propuesto" %>
    <%= p.number_field :proposed, class:"form" %>
  <%= p.hidden_field :reached, :value => -1 %>
<% end %>

I found that this could be reached using JQuery but I don't know how, could someone help me?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
  • 11
  • 2
  • Go ahead and take a look at the HTML output of your loop and write a jQuery function to output it to the desired element `x` times to the desired container. It's difficult to explain more thoroughly than that without knowing precisely what you're going for here. – Aleksandar Misich Nov 11 '17 at 16:38

1 Answers1


You select option will generate html, that is your starting point to write the jquery function. You need to inspect with the chrome developer tolls the html generated in your page

<%= g.select :num_periods, options_for_select([["Mensual", 12], ["Semestral", 6], ["Trimestral", 4], ["Anual", 1]]) %>

it should look like this from the api page of ActionView::Helpers::FormOptionsHelper:

<select name="g[num_periods]" id="g_num_periods">
  <option value="12">Mensual</option>
  <option value="6">Semestral</option>
  <option value="4">Trimestral</option>

so the easy option is, displaying in the view all the input field, and hiding those that are not required based on your needs. So they will all be hidden and you can show the one you need with:

   $('select option:selected').click(function() {
       var option_selected = $(this).text();
       //now you need to find the div to show and use the .show function to display it

this is my jsfiddle

I know this is not a great solution, but I don't have all the info from your code and also, I am not sure that appending div for a form will allow you to do the post request as there is an authenticity_token in the forms that prevents CSRF

Also this give you more info about authenticity token

Fabrizio Bertoglio
  • 5,890
  • 4
  • 16
  • 57