我正在使用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>
这是部分.... _attachment_fileds.tml.erb:
<div class="nested-fields">
<%= form.label :image, required: true %>
<div class="input-group">
<div class="custom-file" style="padding-top: 38px;">
<%= form.input :images, label: false, as: :file, :input_html => { :class => 'custom-file-input', :style=>"cursor: pointer", :id=>"inputGroupFile01"} %>
<label class="custom-file-label" for="inputGroupFile01" id="file-name" style="cursor: pointer;">Choose file</label>
</div>
</div>
<div style="text-align: right;"><%= link_to_remove_association "remove", form %></div>
</div>
一切都很好。
现在,关于使用cocoon
生成的每个字段,我想用标签字段中的choose a file
文本替换已选择的文件的名称。
起初我尝试了下面的内容,但后来我发现cocoon gem
为每个字段生成了不同的id。
<script>
$("#inputGroupFile01").change(function(){
$("#file-name").text(this.files[0].name);
});
</script>
所以现在我有点坚持如何实现上述。任何帮助将非常感谢。
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>
然后你可以写一些像(未经测试的)
$(".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')
我不确定是否只是寻找closest
标签会起作用吗?
$(this).closest('label.custom-file-label')
或者如上所述,使用正确的选择器查找sibling
。