Javascript Rails:文件嵌套字段,显示每个字段上所选文件的名称
我使用Javascript Rails:文件嵌套字段,显示每个字段上所选文件的名称,javascript,jquery,ruby-on-rails,cocoon-gem,Javascript,Jquery,Ruby On Rails,Cocoon Gem,我使用cocoon gem添加带有嵌套字段的图像: <div id="attachments"> <%= f.simple_fields_for :attachments do |attachment| %> <%= render 'products/attachment_fields', form: attachment %> <% end %> <div class="links" id="add
cocoon gem
添加带有嵌套字段的图像:
<div id="attachments">
<%= f.simple_fields_for :attachments do |attachment| %>
<%= render 'products/attachment_fields', form: attachment %>
<% end %>
<div class="links" id="add_attachment" style="display: inline; float: right;">
<%= link_to_add_association 'add more images', f, :attachments, form_name: 'form' %>
</div>
</div>
所以现在我有点被困在如何实现上述功能上。非常感谢您的帮助。html id在页面上应该是唯一的,因此您不能对重复字段使用唯一id。虽然页面可以正确呈现,但在发布表单时,它将忽略重复的id(从而发布不正确/不完整的信息) 其次,使用jquery很容易找到最近的元素 因此,在嵌套字段的部分中,删除所有id,然后编写如下内容
<%= form.input :images, label: false, as: :file,
:input_html => { :class => 'custom-file-input', :style=>"cursor: pointer"} %>
<label class="custom-file-label" style="cursor: pointer;">Choose file</label>
有几个选项,我不确定哪个选择器工作得最好。您可以向上移动,然后选择正确的标签:
$(this).closest('.nested-fields').find('label.custom-file-label')
我不确定仅仅寻找最近的标签是否有效
$(this).closest('label.custom-file-label')
或者像我上面所做的那样,使用正确的选择器查找同级
$(".nested-fields .custom-file-input").change(function(){
$(this).siblings("label.custom-file-label").text(this.files[0].name);
});
$(this).closest('.nested-fields').find('label.custom-file-label')
$(this).closest('label.custom-file-label')