Rails茧宝石:填充多个字段

问题描述 投票:0回答:1

我正在使用Rails应用程序中的cocoon gem。我有两个嵌套字段(选择字段:类别,子类别),当我从第一个选择字段中选择一个值时,另一个将根据该值填充。问题是我为此使用了特定的ID,当我添加更多字段时,由于所有字段最终都具有相同的ID,因此它无法正常工作。我该如何设置,以便每次向表单添加更多嵌套字段时都能正确填充第二个选择字段?

<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" } %>

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

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



$('#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>');
            });
        }
    });
});
javascript jquery ruby-on-rails cocoon-gem
1个回答
0
投票

我会给您的selects类而不是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" } %>
  <%= form.input :subcategories, label: false, :collection => [], :label_method => :name, :value_method => :id, required: true, input_html: { multiple: true, class: "second_dropdown" } %>

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

然后找到相对于第一个选择的第二个选择:

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

尚未测试,但类似的方法应该起作用。

© www.soinside.com 2019 - 2024. All rights reserved.