jQuery UIを使って簡単にダイアログを表示させる方法
ブラウザ上でユーザーに対してちょっとした確認を行いたい場合はJavaScriptのconfirmを用いて「はい」「いいえ」を選択してもらっていたが、それ以外の選択肢の追加であったり、メッセージ内にリンクを設置したい案件があった。ダイアログを設置するのが良さそうなものの、自身で設置したことが無かった。色々調べてみたところjQuery UIが簡単に設置できたので以下に方法をメモ。
サンプル
https://taitan916.info/sample/dialog/
「ダイアログ表示」ボタンをクリックするとダイアログが表示される。その後に「はい」「キャンセル」「その他」「リンク」をクリックすると、ダイアログが非表示となり「●●をクリックしました」と文言が表示される。
ソースコード
<html lang="ja">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>jQuery UIのダイアログサンプル</title>
<link href="//stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
<script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>
<script src="//code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="//stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</head>
<body>
	<a href="javascript:void(0);" class="btn btn-primary" id="dialog_btn">
		ダイアログ表示
	</a>
	<div id="dialog_area" style="display:none;">
		<p>
			ダイアログテストです。<br>
			<a href="javascript:void(0);" id="dialog_link" style="font-weight: bold; color: #f00;">リンク</a>も設置できます。<br>
		</p>
	</div>
	<div id="dialog_result">
	</div>
	<script type="text/javascript" src="//code.jquery.com/jquery-3.5.1.js"></script>
	<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
	<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
	<script>
	$(function(){
		//ダイアログ表示ボタンクリック時
		$('#dialog_btn').click(function(){
			$("#dialog_area").dialog({
				modal:true,
				title:"登録確認",
				buttons: {
					"はい": function() {
						$('#dialog_result').html('はいをクリックしました。');
						$('#dialog_area').dialog('close');
					},
					"キャンセル": function() {
						$('#dialog_result').html('キャンセルをクリックしました。');
						$('#dialog_area').dialog('close');
					},
					"その他":  function() {
						$('#dialog_result').html('その他をクリックしました。');
						$('#dialog_area').dialog('close');
					},
				}
			});
		});
		//ダイアログ内リンククリック時
		$('#dialog_link').click(function(){
			$('#dialog_result').html('リンクをクリックしました。');
			$('#dialog_area').dialog('close');
		});
	});
	</script>
</body>
</html>
3つ目のボタンが設置及びメッセージ内にリンクを設置し、それぞれのクリック時に異なる処理を行える。
リファレンス
https://js.studio-kingdom.com/jqueryui/widgets/dialog
所感
jQuery UIはカレンダーピッカーを使うまで何となく食わず嫌いしていたけどすごく便利かも。
関連記事
- 
					
													  
- 
					formのpasswordとtextをjQueryで切り替える方法formでtype="password"を指定していると内容を入力した際に「●● ... 
- 
					
													  
- 
					フォームの入力・選択内容を自動保存してくれる「Garlicjs」プラグインの利用方法お問い合わせページ等、フォームを設置したページで入力・選択した内容を保存したい。 ... 
- 
					
													  
- 
					jQuery.uploadでリアルタイムプレビューやりたい事は、 ・<input type="file">で画像を選択 ... 
- 
					
													  
- 
					Ajaxを使用する際の注意Ajaxで特にJSONPを使う際によくミスることがあるので 注意点をまとめておく ... 
- 
					
													  
- 
					Lightboxで画像拡大時に文字タイトルとリンクをつけるlightboxで画像をクリックして拡大した際に、文字タイトルとその文字にリンク ...