0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

学習39日目

Last updated at Posted at 2025-07-12

内容

画像選択画面で画像を変更した場合のプレビュー処理

前提

  • 画像投稿機能(active storage)実装済
  • 画像プレビュー機能(javascript)実装済
  • 追記部分以外の記述は省略

手順

imgを取得し、既にimgがあれば削除する処理を追記。

xxxx.html.erb

<script>
   let imageInput = document.getElementById("district_image")
   let imagePreview  = document.getElementById("image_preview")
   imageInput.addEventListener('change', (e) => {
       let file = e.target.files[0];
       let blob = window.URL.createObjectURL(file);
       if (document.querySelector('img')) {
           let img = document.querySelector('img')
           img.remove()
       }
       let img = document.createElement('img');
       img.setAttribute('src', blob);
       img.setAttribute('style', 'width: 150px; height: 150px;')
       imagePreview.appendChild(img);
   })
</script>

コメント

わざわざ既存のimgを削除しなくても、srcを新しいblobに置き換えれば問題なさそう。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?