简体   繁体   English

Rails cocoon gem:填充多个字段

[英]Rails cocoon gem: populate multiple fields

I'm using the cocoon gem on my rails app and I have two nested fields inside a form (categories, subcategories).我在我的 rails 应用程序上使用cocoon gem ,我在表单中有两个嵌套字段(类别、子类别)。 Initially I'm showing the first one only and the second one is hidden.最初我只显示第一个,第二个是隐藏的。 Each time the first select fields has subcategories the second field gets populated and appears.每次第一个选择字段有子类别时,第二个字段都会填充并出现。

The nested fields:嵌套字段:

<div class="nested-fields">

  <%= form.input :category, collection: @categories, as: :grouped_select, group_method: :children, :label => false, :include_blank => true, input_html: { id: "first_dropdown" } %>

<div class="show_hide">
  <%= form.input :subcategories, label: false, :collection => [], :label_method => :name, :value_method => :id, required: true, input_html: { multiple: true, id: "second_dropdown" } %>
</div>

  <div class="links">
    <%= link_to_remove_association "Remove", form %>
  </div>
</div>

This is the code to initially hide the second field这是最初隐藏第二个字段的代码

$('#first_dropdown').keyup(function() {

    if ($(this).val().length == 0) {
        $('.show_hide').hide();
    }
}).keyup();

This is the code to show the second select input when the first select input has subcategories:这是当第一个选择输入具有子类别时显示第二个选择输入的代码:

def select_item
  category = Category.find params[:category_id]
  render json: category.children
end


$('#first_dropdown').on('change', function() {
    $.ajax({
        url: 'categories/select_item?category_id=' + $(this).val(),
        dataType: 'json',
        success: function(data) {
            let childElement = $('#second_dropdown');
            if( data.length === 0 ) {
                $('.show_hide').hide();
            } else {
                $('.show_hide').show();
            }
            childElement.html('');
            data.forEach(function(v) {
                let id = v.id;
                let name = v.name;
                childElement.append('<option value="' + id + '">' + name + '</option>');
            });
        }
    });
});

Everything works well for the initial opened field.对于初始打开的字段,一切正常。 But when I add more fields and select a value inside any of the first select fields it populates all of the second fields according to that value.但是,当我添加更多字段并在任何第一个选择字段中选择一个值时,它会根据该值填充所有第二个字段。 I think it's because I'm using specific id's for this and when I add more fields, all of them end up having the same id's.我认为这是因为我为此使用了特定的 id,当我添加更多字段时,它们最终都具有相同的 id。 How can I set this up so I properly populate the second select field each time I add more nested fields to the form?如何设置它以便每次向表单添加更多嵌套字段时正确填充第二个选择字段?

I'd give your selects classes instead of ids:我会给你的选择类而不是 id:

<div class="nested-fields">
  <%= form.input :category, collection: @categories, as: :grouped_select, group_method: :children,
                 label: false, include_blank: true, input_html: { class: "first_dropdown" } %>

  <% if f.object.category && f.object.category.sub_categories.length > 0 %>
    <div class="show_hide">
      <%= form.input :subcategories, label: false, collection: form.object.category.subcategories, label_method: :name,
                     value_method: :id, required: true, input_html: { multiple: true, class: "second_dropdown" } %>
    </div>
  <% else %>
    <div class="show_hide" style="display: none;">
      <%= form.input :subcategories, label: false, collection: [], label_method: :name,
                     value_method: :id, required: true, input_html: { multiple: true, class: "second_dropdown" } %>
    </div>
  <% end %>
  <div class="links">
    <%= link_to_remove_association "Remove", form %>
  </div>
</div>

then find the second select relative to the first one adding this to a page specific js file:然后找到相对于第一个选择的第二个选择,将其添加到页面特定的 js 文件中:

$(document).on('turbolinks:load cocoon:after-insert', function(){
  $('.first_dropdown').off('change').on('change', function(){
    let $this = $(this);
    let $second = $this.closest('.nested-fields').find('.second_dropdown');
    $second.children().remove();
    $second.closest('.show_hide').hide();
    if ($this.val() !== '') {
      $.ajax({
        url: 'categories/select_item?category_id=' + $(this).val(),
        dataType: 'json',
        success: function(data){
          if (data.length > 0) {
            $second.append('<option value=""></option>');
            data.forEach(function(v) {
              let id = v.id;
              let name = v.name;
              $second.append('<option value="' + id + '">' + name + '</option>');
            });
            $second.closest('.show_hide').show();
          }
        }
      })
    }
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM