前提・実現したいこと
最近、jQueryを学び始めたものです。
Railsでプレビュー画面をコントローラーで複数作って、それぞれにプレビュー表示をjQueyで行いたいのですが、書き方に煮詰まっています。
ネストさせたname属性が変化しているので、そこの各数字に指定するといった方法で探したら、参考サイトが見つからなかったので質問させていてだきました。
わかる方がいらしゃったら回答いただけると非常に助かります。よろしくお願いいたします。
最初のプレビュー画面では、プレビュー画面が表示されてます。
発生している問題・エラーメッセージ
jqueryのプレビューの複数表示
new.js
$( document ).on('turbolinks:load', function() { function readURL(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function (e) { $('#product_img_prev').attr('src', e.target.result); } reader.readAsDataURL(input.files[0]); } } $("#product_img").change(function(){ $('#product_img_prev').removeClass('hidden'); $('.product_present_img').remove(); readURL(this); }); });
jqueryのプレビューの複数表示
new.js
$( document ).on('turbolinks:load', function() { function readURL(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function (e) { $('#product_img_prev').attr('src', e.target.result); } reader.readAsDataURL(input.files[0]); } } $("#product_img").change(function(){ $('#product_img_prev').removeClass('hidden'); $('.product_present_img').remove(); readURL(this); }); });
new.html.haml
= form_for @product do |f| .sell-product__container__form .upload-image %h3.upload-image__head 出品画像 %span.require.upload-image__head__require 必須 %p 最大10枚までアップロードできます = f.fields_for :product_images do |i| .upload-image__box .upload-image__box__drop .upload-image__box__drop__display %ul %label .upload-image__box__file %img.hidden#product_img_prev = image_tag '', class: 'avatar_present_img' = i.file_field :image_url, multiple: true, class: 'upload-image__box__file__input',id:'product_img', type: :file %pre.upload-image__box__file__description ドラッグアンドドロップ またはクリックしてファイルをアップロード
new.html.haml
def new @product = Product.new 10.times{@product.product_images.build} end
model
has_many :product_images, dependent: :destroy accepts_nested_attributes_for :product_images, allow_destroy: true
ここに問題に対して試したことを記載してください。
補足情報(FW/ツールのバージョンなど)
10回繰り返しの指定をしているので、[0]の値が10までそれぞれのプレビュー画面で変化します
<input multiple="multiple" class="upload-image__box__file__input" id="product_img" type="file" name="product[product_images_attributes][0][image_url][]">
あなたの回答
tips
プレビュー