5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Bootstrap3】モーダルのJavaScript呼び出しでデータを渡す

Last updated at Posted at 2018-06-07

button要素で呼び出す、またはa要素で呼び出す場合は、「data-*」属性を使ってモーダルにデータを渡すことができます。

参考: モーダル ≪ JavaScript ≪ Bootstrap3日本語リファレンス

しかし、JavaScriptで呼び出す場合はどのようにして「data-*」属性のデータを参照すればよいでしょう?

以下のように書くことで参照できます。

HTML
<button type="button" id="sampleButton" class="btn btn-primary btn-lg" data-recipient="受信者名">
	モーダル・ダイアログ 呼び出し
</button>

<!-- モーダル・ダイアログ -->
<div class="modal fade" id="sampleModal" tabindex="-1">
	<div class="modal-dialog">
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal"><span>×</span></button>
				<h4 class="modal-title">タイトル</h4>
			</div>
			<div class="modal-body">
				本文
			</div>
			<div class="modal-footer">
				<button type="button" class="btn btn-default" data-dismiss="modal">閉じる</button>
				<button type="button" class="btn btn-primary">ボタン</button>
			</div>
		</div>
	</div>
</div>
JavaScript
$( function() {
	$('#sampleButton').click( function (e) {
		$('#sampleModal').modal({}, e.target);
	});
});
$('#sampleModal').on('show.bs.modal', function (event) {
	var button = $(event.relatedTarget);
	var recipient = button.data('recipient');
	var modal = $(this);
	modal.find('.modal-title').text(recipient + 'へのメッセージ');
});

キモは$('#sampleModal').modal({}, e.target);の部分。modal()の第2引数にオブジェクトを渡すことができます。(第1引数はモーダルのオプション)

5
5
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
5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?