teratail header banner
teratail header banner
質問するログイン新規登録

質問編集履歴

1

ソースコード

2020/07/07 13:24

投稿

Ponimaru
Ponimaru

スコア6

title CHANGED
File without changes
body CHANGED
@@ -8,4 +8,52 @@
8
8
  id名、クラス名の確認を行いましたが特に間違いはありませんでした。
9
9
 
10
10
  ### 該当のソースコード
11
+ ```haml
12
+ //new.html.haml
13
+
14
+ = form_for @product do |f|
15
+ 商品名#{f.text_field :name}
16
+ %br/
17
+ 価格#{f.number_field :price}
18
+ %br/
19
+ #image-box
20
+ = f.fields_for :images do |image|
21
+ .js-file_group{"data-index" => "#{image.index}"}
22
+ = image.file_field :src, class: 'js-file'
23
+ %br/
24
+ %span.js-remove 削除
25
+ = f.submit
26
+ ```
27
+
28
+ ```javascript
29
+ $(document).on('turbolinksload', ()=> {
30
+ // 画像用のinputを生成する関数
31
+ const buildFileField = (index)=> {
32
+ const html = `<div class="js-file_group" data-index="${index}">
33
+ <input class="js-file" type="file"
34
+ name="product[images_attributes][${index}][src]"
35
+ id="product_images_attributes_${index}_src">
36
+ <br>
37
+ <span class="js-remove">削除</div>
38
+ </div>`;
39
+ return html;
40
+ }
41
+
42
+ // file_fieldのnameに動的なindexをつける為の配列
43
+ let fileIndex = [1,2,3,4,5,6,7,8,9,10];
44
+
11
- [ソースコード](https://gyazo.com/ee2e9dfaa80fab073003986a9ad6e759)
45
+ $('#image-box').on('change', '.js-file', function(e) {
46
+ // fileIndexの先頭の数字を使ってinputを作る
47
+ $('#image-box').append(buildFileField(fileIndex[0]));
48
+ fileIndex.shift();
49
+ // 末尾の数に1足した数を追加する
50
+ fileIndex.push(fileIndex[fileIndex.length - 1] + 1)
51
+ });
52
+
53
+ $('#image-box').on('click', '.js-remove', function() {
54
+ $(this).parent().remove();
55
+ // 画像入力欄が0個にならないようにしておく
56
+ if ($('.js-file').length == 0) $('#image-box').append(buildFileField(fileIndex[0]));
57
+ });
58
+ });
59
+ ```