jqueryruby-on-railsrubycocoon-gem

jQuery trigger all instances on a nested form rails cocoon


I have a form with the following which are nested fields using cacoon

enter image description here

I have default fields and a conditional to show more fields if an option is selected ie. Rocket League like so

enter image description here

However, as you can see from the screenshot only one instance of a tournament standing is actually switching fields.

So my question is, how do I make every instance change?

Here is my code:

$(document).on("change", ".ts_select", function(event) {
  if (this.value == '1') {
    $('#default-fields').hide()
    $('#rocket-fields').show()
  } else {
    $('#default-fields').show()
    $('#rocket-fields').hide()
  }
})
<div id="default-fields" class="grid grid-cols-1 md:grid-cols-4">
    <%= render partial: "tournaments/fpartials/default", tournament: @tournament, locals: { f: f } %>
  </div>

  <div id="rocket-fields" class="grid grid-cols-1 md:grid-cols-4 hidden">
    <%= render partial: "tournaments/fpartials/rocket_league_fields", tournament: @tournament, locals: { f: f } %>
  </div>

Solution

  • The jQuery selector you are using picks the first matching HTML element. So, in your case you are selecting the first divs with the IDs 'default-fields' and 'rocket-fields'.

    Assuming all your team fields are just wrapped in divs with those IDs, you can use a different selector to find all instances:

    $("[id='default-fields']").hide();
    $("[id='default-fields']").show();
    

    Check out the jQuery documentation if you want to know more about how selectors work.