【发布时间】:2020-03-07 10:38:53
【问题描述】:
我在我的 rails 应用程序上使用cocoon gem,并且我在表单中有两个嵌套字段(类别、子类别)。最初我只显示第一个,第二个是隐藏的。每次第一个选择字段具有子类别时,都会填充并显示第二个字段。
嵌套字段:
<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>
这是最初隐藏第二个字段的代码
$('#first_dropdown').keyup(function() {
if ($(this).val().length == 0) {
$('.show_hide').hide();
}
}).keyup();
这是当第一个选择输入有子类别时显示第二个选择输入的代码:
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>');
});
}
});
});
对于初始打开的字段,一切正常。但是,当我添加更多字段并在任何第一个选择字段中选择一个值时,它会根据该值填充所有第二个字段。我认为这是因为我为此使用了特定的 ID,当我添加更多字段时,所有字段最终都具有相同的 ID。如何进行设置,以便每次向表单添加更多嵌套字段时正确填充第二个选择字段?
【问题讨论】:
标签: javascript jquery ruby-on-rails cocoon-gem