もくじ
「入力フォームに入力した内容を、送信する前に確認画面(モーダル)を出したい」
そんなときに、jQueryを使って入力内容を取得してモーダルに渡す方法をご紹介します。
完成図
はじめに完成系をみましょう。スタイルはbootstrapを利用しています。
入力フォーム
テキストを入力
確認モーダル
HTML
<form action="#" method="POST"> @csrf <div class="form-group"> <label for="formTitle" class="col-form-label">タイトル</label> <input type="text" class="form-control" id="formTitle" name="title" placeholder="タイトル"> </div> <div class="form-group"> <label for="formBody" class="col-form-label">本文</label> <textarea id="formBody" name="body" class="form-control" rows="10" placeholder="本文"></textarea> </div> <div class="form-group row justify-content-center"> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">送信</button> </div> <!-- モーダルの設定 --> <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel"> <div class="modal-dialog modal-dialog-scrollable"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">入力内容の確認</h5> <button type="button" class="close" data-dismiss="modal" aria-label="閉じる"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body"> <div> <p class="text-muted">タイトル</p> <p class="px-2" id="modalTitle"></p> </div> <div> <p class="text-muted">本文</p> <p class="px-2" id="modalBody"></p> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">閉じる</button> <button type="button" class="btn btn-primary">OK</button> </div><!-- /.modal-footer --> </div><!-- /.modal-content --> </div><!-- /.modal-dialog --> </div><!-- /.modal --> </form>
特に注意するような書き方はありません。
CSS
#modalBody { white-space: pre-wrap; }
white-space: pre-wrap;
これを指定することで、改行コードなども認識してくれるようになります。DBにも、エスケープシーケンスを使った改行(\n
)としてが登録されます。
jQuery側で.text()
を指定しているので本来改行コードなどを認識できなくなります。仮にこのスタイルを指定しなかった場合こうなります。↓
もし改行させたくないならこの記述は不要になります。
JavaScript(jQuery)
$(function() { $('#exampleModal').on('show.bs.modal', function () { var title = $('#formTitle').val() var body = $('#formBody').val() var modal = $(this) modal.find('#modalTitle').text(title) modal.find('#modalBody').text(body) }) })
.val()
$('#formTitle').val()
で、id="formTitle"
のvalue(入力値)を取得します。つまり、タイトルに入力した内容を取得しています。本文も同様です。
.find() .text()
.find('#modalTitle').text(title)
は、id="modalTitle"
が指定されている要素に入力された値をテキストとして挿入します。
注意すべきは、.html()
ではなく.text()
にすることです。.html()
にしてしまうと、スクリプトなど入力送信できてしまいます。悪意を持った人間によってウイルスを埋め込まれる可能性もあるので、すべての入力値を文字列として取得しています。