LoginSignup
0
0

More than 3 years have passed since last update.

あっさり読むrails 番外(image)

Posted at

はじめに

以前の記事の応用で、画像アドレスをフォームに入力すると、自動的に画像が表示されるようにします。

前提

前記事をそのまま修正します。

実行

ビューファイルを次の様に修正します。

sample.haml.html
= form_with model:@sample, local: true do |f|
  = f.text_area :name, placeholder: "サンプル", class: "sample-form"

.add-image

add-textadd-imageに変えただけです。

JSファイルを次の様に書きます。

sample.js
$(function(){
 $(".sample-form").on("change" functon(){
   var image = $(this).val();
   let html = `
     <div class = "add-image__sample">
       <img src = "$(image)" height = "500" //heightはなんでもいい
     </div>
   `
   ;
   $(".add-image").append(html);
 })
});

大雑把な流れとしては、
1.フォーム(.sample-form)の中身が変わった("change")時=画像アドレスを貼り付けた時
2.その値をimageに代入し
3.それを表示させるhtmlデータを変数に代入し
4..add-imageに追加(append)する

となります。

本当は、別の画像アドレスを貼り付ける時に元の画像を削除する必要がありますが、
ひとまずはこれで非同期の画像表示ができます。

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