트위터 부트스트랩을 사용하여 모달/대화 상자에서 삭제를 확인하시겠습니까?
데이터베이스 행에 연결된 행의 HTML 테이블이 있습니다.각 행에 대해 "행 삭제" 링크를 설정하고 싶은데, 사용자에게 미리 확인하고 싶습니다.
트위터 부트스트랩 모달 대화 상자를 사용하여 이를 수행할 수 있는 방법이 있습니까?
GET 레시피
이 작업에는 이미 사용 가능한 플러그인 및 부트스트랩 확장을 사용할 수 있습니다.또는 코드 3줄만으로 직접 확인 팝업을 만들 수 있습니다.이것을 확인해 보세요.
가정해 .data-href
에 href
또는 삭제 확인을 원하는 단추:
<a href="#" data-href="delete.php?id=23" data-toggle="modal" data-target="#confirm-delete">Delete record #23</a>
<button class="btn btn-default" data-href="/delete.php?id=54" data-toggle="modal" data-target="#confirm-delete">
Delete record #54
</button>
여기서#confirm-delete
HTML의 모달 팝업 div를 가리킵니다. "확인" 버튼은 다음과 같이 구성되어 있어야 합니다.
<div class="modal fade" id="confirm-delete" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
...
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<a class="btn btn-danger btn-ok">Delete</a>
</div>
</div>
</div>
</div>
이제 삭제 작업을 확인하려면 다음과 같은 작은 Javascript만 있으면 됩니다.
$('#confirm-delete').on('show.bs.modal', function(e) {
$(this).find('.btn-ok').attr('href', $(e.relatedTarget).data('href'));
});
곧.show.bs.modal
delete 버튼 삭제튼버트이벤튼버▁event▁delete.href
는 해당 레코드 ID를 가진 URL로 설정됩니다.
데모: http://plnkr.co/edit/NePR0BQf3VmKtuMmhVR7?p=preview
POST 레시피
경우에 따라 GET보다 POST 또는 DELETE 요청을 수행해야 할 수도 있다는 것을 알고 있습니다.코드가 너무 많지 않아도 여전히 꽤 간단합니다.이 접근 방식을 사용하여 아래 데모를 살펴보십시오.
// Bind click to OK button within popup
$('#confirm-delete').on('click', '.btn-ok', function(e) {
var $modalDiv = $(e.delegateTarget);
var id = $(this).data('recordId');
$modalDiv.addClass('loading');
$.post('/api/record/' + id).then(function() {
$modalDiv.modal('hide').removeClass('loading');
});
});
// Bind to modal opening to set necessary data properties to be used to make request
$('#confirm-delete').on('show.bs.modal', function(e) {
var data = $(e.relatedTarget).data();
$('.title', this).text(data.recordTitle);
$('.btn-ok', this).data('recordId', data.recordId);
});
// Bind click to OK button within popup
$('#confirm-delete').on('click', '.btn-ok', function(e) {
var $modalDiv = $(e.delegateTarget);
var id = $(this).data('recordId');
$modalDiv.addClass('loading');
setTimeout(function() {
$modalDiv.modal('hide').removeClass('loading');
}, 1000);
// In reality would be something like this
// $modalDiv.addClass('loading');
// $.post('/api/record/' + id).then(function() {
// $modalDiv.modal('hide').removeClass('loading');
// });
});
// Bind to modal opening to set necessary data properties to be used to make request
$('#confirm-delete').on('show.bs.modal', function(e) {
var data = $(e.relatedTarget).data();
$('.title', this).text(data.recordTitle);
$('.btn-ok', this).data('recordId', data.recordId);
});
.modal.loading .modal-content:before {
content: 'Loading...';
text-align: center;
line-height: 155px;
font-size: 20px;
background: rgba(0, 0, 0, .8);
position: absolute;
top: 55px;
bottom: 0;
left: 0;
right: 0;
color: #EEE;
z-index: 1000;
}
<script data-require="jquery@*" data-semver="2.0.3" src="//code.jquery.com/jquery-2.0.3.min.js"></script>
<script data-require="bootstrap@*" data-semver="3.1.1" src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<link data-require="bootstrap-css@3.1.1" data-semver="3.1.1" rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" />
<div class="modal fade" id="confirm-delete" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Confirm Delete</h4>
</div>
<div class="modal-body">
<p>You are about to delete <b><i class="title"></i></b> record, this procedure is irreversible.</p>
<p>Do you want to proceed?</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-danger btn-ok">Delete</button>
</div>
</div>
</div>
</div>
<a href="#" data-record-id="23" data-record-title="The first one" data-toggle="modal" data-target="#confirm-delete">
Delete "The first one", #23
</a>
<br />
<button class="btn btn-default" data-record-id="54" data-record-title="Something cool" data-toggle="modal" data-target="#confirm-delete">
Delete "Something cool", #54
</button>
데모: http://plnkr.co/edit/V4GUuSueuuxiGr4L9LmG?p=preview
부트스트랩 2.3
여기 부트스트랩 2.3 모달에 대한 이 질문에 답할 때 만든 코드의 원본 버전이 있습니다.
$('#modal').on('show', function() {
var id = $(this).data('id'),
removeBtn = $(this).find('.danger');
removeBtn.attr('href', removeBtn.attr('href').replace(/(&|\?)ref=\d*/, '$1ref=' + id));
});
데모: http://jsfiddle.net/MjmVr/1595/
http://bootboxjs.com/ - 부트스트랩 3.0.0으로 최신 작동
가장 간단한 예는 다음과 같습니다.
bootbox.alert("Hello world!");
사이트에서:
라이브러리는 네이티브 JavaScript 등가물을 모방하도록 설계된 세 가지 방법을 제공합니다.정확한 메소드 서명은 레이블을 사용자 정의하고 기본값을 지정하기 위해 다양한 매개 변수를 사용할 수 있기 때문에 유연하지만 가장 일반적으로 다음과 같이 호출됩니다.
bootbox.alert(message, callback)
bootbox.prompt(message, callback)
bootbox.confirm(message, callback)
다음은 실행 중인 코드 조각입니다(아래 "실행 코드 조각" 클릭).
$(function() {
bootbox.alert("Hello world!");
});
<!-- required includes -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>
<!-- bootbox.js at 4.4.0 -->
<script src="https://rawgit.com/makeusabrew/bootbox/f3a04a57877cab071738de558581fbc91812dce9/bootbox.js"></script>
// ---------------------------------------------------------- Generic Confirm
function confirm(heading, question, cancelButtonTxt, okButtonTxt, callback) {
var confirmModal =
$('<div class="modal hide fade">' +
'<div class="modal-header">' +
'<a class="close" data-dismiss="modal" >×</a>' +
'<h3>' + heading +'</h3>' +
'</div>' +
'<div class="modal-body">' +
'<p>' + question + '</p>' +
'</div>' +
'<div class="modal-footer">' +
'<a href="#" class="btn" data-dismiss="modal">' +
cancelButtonTxt +
'</a>' +
'<a href="#" id="okButton" class="btn btn-primary">' +
okButtonTxt +
'</a>' +
'</div>' +
'</div>');
confirmModal.find('#okButton').click(function(event) {
callback();
confirmModal.modal('hide');
});
confirmModal.modal('show');
};
// ---------------------------------------------------------- Confirm Put To Use
$("i#deleteTransaction").live("click", function(event) {
// get txn id from current table row
var id = $(this).data('id');
var heading = 'Confirm Transaction Delete';
var question = 'Please confirm that you wish to delete transaction ' + id + '.';
var cancelButtonTxt = 'Cancel';
var okButtonTxt = 'Confirm';
var callback = function() {
alert('delete confirmed ' + id);
};
confirm(heading, question, cancelButtonTxt, okButtonTxt, callback);
});
저는 그것이 매우 오래된 질문이라는 것을 깨달았지만, 오늘 부트스트랩 모델을 처리하는 더 효율적인 방법이 궁금했기 때문입니다.몇 가지 조사를 해본 결과 위에 나와 있는 솔루션보다 더 나은 솔루션을 발견했습니다. 이 링크에서 찾을 수 있습니다.
http://www.petefreitag.com/item/809.cfm
먼저 jquery를 로드합니다.
$(document).ready(function() {
$('a[data-confirm]').click(function(ev) {
var href = $(this).attr('href');
if (!$('#dataConfirmModal').length) {
$('body').append('<div id="dataConfirmModal" class="modal" role="dialog" aria-labelledby="dataConfirmLabel" aria-hidden="true"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button><h3 id="dataConfirmLabel">Please Confirm</h3></div><div class="modal-body"></div><div class="modal-footer"><button class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button><a class="btn btn-primary" id="dataConfirmOK">OK</a></div></div>');
}
$('#dataConfirmModal').find('.modal-body').text($(this).attr('data-confirm'));
$('#dataConfirmOK').attr('href', href);
$('#dataConfirmModal').modal({show:true});
return false;
});
});
그런 다음 href에 아무 질문이나 하고 확인합니다.
<a href="/any/url/delete.php?ref=ID" data-confirm="Are you sure you want to delete?">Delete</a>
이러한 방식으로 확인 모달은 훨씬 더 보편적이므로 웹 사이트의 다른 부분에서 쉽게 재사용할 수 있습니다.
@Jousby의 솔루션 덕분에 제 솔루션도 작동할 수 있었지만 공식 예제에서 설명한 것처럼 올바르게 렌더링하려면 그의 솔루션의 부트스트랩 모달 마크업을 약간 개선해야 했습니다.
가 수정한 버전입니다.confirm
정상적으로 작동한 기능:
/* Generic Confirm func */
function confirm(heading, question, cancelButtonTxt, okButtonTxt, callback) {
var confirmModal =
$('<div class="modal fade">' +
'<div class="modal-dialog">' +
'<div class="modal-content">' +
'<div class="modal-header">' +
'<a class="close" data-dismiss="modal" >×</a>' +
'<h3>' + heading +'</h3>' +
'</div>' +
'<div class="modal-body">' +
'<p>' + question + '</p>' +
'</div>' +
'<div class="modal-footer">' +
'<a href="#!" class="btn" data-dismiss="modal">' +
cancelButtonTxt +
'</a>' +
'<a href="#!" id="okButton" class="btn btn-primary">' +
okButtonTxt +
'</a>' +
'</div>' +
'</div>' +
'</div>' +
'</div>');
confirmModal.find('#okButton').click(function(event) {
callback();
confirmModal.modal('hide');
});
confirmModal.modal('show');
};
/* END Generic Confirm func */
저는 이것이 유용하고 사용하기 쉽다는 것을 알았고, 게다가 예뻐 보입니다: http://maxailloud.github.io/confirm-bootstrap/ .
이를 사용하려면 페이지에 .js 파일을 포함한 다음 다음을 실행합니다.
$('your-link-selector').confirmModal();
다양한 옵션을 적용하여 삭제를 확인할 때 더 보기 좋게 하기 위해 다음과 같은 방법을 사용합니다.
$('your-link-selector').confirmModal({
confirmTitle: 'Please confirm',
confirmMessage: 'Are you sure you want to delete this?',
confirmStyle: 'danger',
confirmOk: '<i class="icon-trash icon-white"></i> Delete',
confirmCallback: function (target) {
//perform the deletion here, or leave this option
//out to just follow link..
}
});
bootbox.js 라이브러리를 사용하여 이러한 유형의 작업을 쉽게 처리할 수 있습니다.먼저 부트박스 JS 파일을 포함해야 합니다.그런 다음 이벤트 핸들러 함수에 다음 코드를 입력합니다.
bootbox.confirm("Are you sure to want to delete , function(result) {
//here result will be true
// delete process code goes here
});
공식 부트박스js 사이트
다음 솔루션이 bootbox.js보다 더 낫습니다. 왜냐하면
- bootbox.js가 할 수 있는 모든 것을 할 수 있습니다.
- 사용 구문이 더 단순합니다.
- 오류, 경고 또는 정보를 사용하여 메시지 색상을 우아하게 제어할 수 있습니다.
- 부트박스는 986줄이고, 내것은 110줄입니다.
digimango.js:
const dialogTemplate = '\
<div class ="modal" id="digimango_messageBox" role="dialog">\
<div class ="modal-dialog">\
<div class ="modal-content">\
<div class ="modal-body">\
<p class ="text-success" id="digimango_messageBoxMessage">Some text in the modal.</p>\
<p><textarea id="digimango_messageBoxTextArea" cols="70" rows="5"></textarea></p>\
</div>\
<div class ="modal-footer">\
<button type="button" class ="btn btn-primary" id="digimango_messageBoxOkButton">OK</button>\
<button type="button" class ="btn btn-default" data-dismiss="modal" id="digimango_messageBoxCancelButton">Cancel</button>\
</div>\
</div>\
</div>\
</div>';
// See the comment inside function digimango_onOkClick(event) {
var digimango_numOfDialogsOpened = 0;
function messageBox(msg, significance, options, actionConfirmedCallback) {
if ($('#digimango_MessageBoxContainer').length == 0) {
var iDiv = document.createElement('div');
iDiv.id = 'digimango_MessageBoxContainer';
document.getElementsByTagName('body')[0].appendChild(iDiv);
$("#digimango_MessageBoxContainer").html(dialogTemplate);
}
var okButtonName, cancelButtonName, showTextBox, textBoxDefaultText;
if (options == null) {
okButtonName = 'OK';
cancelButtonName = null;
showTextBox = null;
textBoxDefaultText = null;
} else {
okButtonName = options.okButtonName;
cancelButtonName = options.cancelButtonName;
showTextBox = options.showTextBox;
textBoxDefaultText = options.textBoxDefaultText;
}
if (showTextBox == true) {
if (textBoxDefaultText == null)
$('#digimango_messageBoxTextArea').val('');
else
$('#digimango_messageBoxTextArea').val(textBoxDefaultText);
$('#digimango_messageBoxTextArea').show();
}
else
$('#digimango_messageBoxTextArea').hide();
if (okButtonName != null)
$('#digimango_messageBoxOkButton').html(okButtonName);
else
$('#digimango_messageBoxOkButton').html('OK');
if (cancelButtonName == null)
$('#digimango_messageBoxCancelButton').hide();
else {
$('#digimango_messageBoxCancelButton').show();
$('#digimango_messageBoxCancelButton').html(cancelButtonName);
}
$('#digimango_messageBoxOkButton').unbind('click');
$('#digimango_messageBoxOkButton').on('click', { callback: actionConfirmedCallback }, digimango_onOkClick);
$('#digimango_messageBoxCancelButton').unbind('click');
$('#digimango_messageBoxCancelButton').on('click', digimango_onCancelClick);
var content = $("#digimango_messageBoxMessage");
if (significance == 'error')
content.attr('class', 'text-danger');
else if (significance == 'warning')
content.attr('class', 'text-warning');
else
content.attr('class', 'text-success');
content.html(msg);
if (digimango_numOfDialogsOpened == 0)
$("#digimango_messageBox").modal();
digimango_numOfDialogsOpened++;
}
function digimango_onOkClick(event) {
// JavaScript's nature is unblocking. So the function call in the following line will not block,
// thus the last line of this function, which is to hide the dialog, is executed before user
// clicks the "OK" button on the second dialog shown in the callback. Therefore we need to count
// how many dialogs is currently showing. If we know there is still a dialog being shown, we do
// not execute the last line in this function.
if (typeof (event.data.callback) != 'undefined')
event.data.callback($('#digimango_messageBoxTextArea').val());
digimango_numOfDialogsOpened--;
if (digimango_numOfDialogsOpened == 0)
$('#digimango_messageBox').modal('hide');
}
function digimango_onCancelClick() {
digimango_numOfDialogsOpened--;
if (digimango_numOfDialogsOpened == 0)
$('#digimango_messageBox').modal('hide');
}
digimango.messagebox.js를 사용하는 방법
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>A useful generic message box</title>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="~/Content/bootstrap.min.css" media="screen" />
<script src="~/Scripts/jquery-1.10.2.min.js" type="text/javascript"></script>
<script src="~/Scripts/bootstrap.js" type="text/javascript"></script>
<script src="~/Scripts/bootbox.js" type="text/javascript"></script>
<script src="~/Scripts/digimango.messagebox.js" type="text/javascript"></script>
<script type="text/javascript">
function testAlert() {
messageBox('Something went wrong!', 'error');
}
function testAlertWithCallback() {
messageBox('Something went wrong!', 'error', null, function () {
messageBox('OK clicked.');
});
}
function testConfirm() {
messageBox('Do you want to proceed?', 'warning', { okButtonName: 'Yes', cancelButtonName: 'No' }, function () {
messageBox('Are you sure you want to proceed?', 'warning', { okButtonName: 'Yes', cancelButtonName: 'No' });
});
}
function testPrompt() {
messageBox('How do you feel now?', 'normal', { showTextBox: true }, function (userInput) {
messageBox('User entered "' + userInput + '".');
});
}
function testPromptWithDefault() {
messageBox('How do you feel now?', 'normal', { showTextBox: true, textBoxDefaultText: 'I am good!' }, function (userInput) {
messageBox('User entered "' + userInput + '".');
});
}
</script>
</head>
<body>
<a href="#" onclick="testAlert();">Test alert</a> <br/>
<a href="#" onclick="testAlertWithCallback();">Test alert with callback</a> <br />
<a href="#" onclick="testConfirm();">Test confirm</a> <br/>
<a href="#" onclick="testPrompt();">Test prompt</a><br />
<a href="#" onclick="testPromptWithDefault();">Test prompt with default text</a> <br />
</body>
</html>

비교적 큰 프로젝트의 경우 재사용 가능한 것이 필요할 수 있습니다.이것은 SO의 도움으로 온 것입니다.
confirmDelete.jsp
<!-- Modal Dialog -->
<div class="modal fade" id="confirmDelete" role="dialog" aria-labelledby="confirmDeleteLabel"
aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"
aria-hidden="true">×</button>
<h4 class="modal-title">Delete Parmanently</h4>
</div>
<div class="modal-body" style="height: 75px">
<p>Are you sure about this ?</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-danger" id="confirm-delete-ok">Ok
</button>
</div>
</div>
</div>
<script type="text/javascript">
var url_for_deletion = "#";
var success_redirect = window.location.href;
$('#confirmDelete').on('show.bs.modal', function (e) {
var message = $(e.relatedTarget).attr('data-message');
$(this).find('.modal-body p').text(message);
var title = $(e.relatedTarget).attr('data-title');
$(this).find('.modal-title').text(title);
if (typeof $(e.relatedTarget).attr('data-url') != 'undefined') {
url_for_deletion = $(e.relatedTarget).attr('data-url');
}
if (typeof $(e.relatedTarget).attr('data-success-url') != 'undefined') {
success_redirect = $(e.relatedTarget).attr('data-success-url');
}
});
<!-- Form confirm (yes/ok) handler, submits form -->
$('#confirmDelete').find('.modal-footer #confirm-delete-ok').on('click', function () {
$.ajax({
method: "delete",
url: url_for_deletion,
}).success(function (data) {
window.location.href = success_redirect;
}).fail(function (error) {
console.log(error);
});
$('#confirmDelete').modal('hide');
return false;
});
<script/>
Page.jsp 재사용
<a href="#" class="table-link danger"
data-toggle="modal"
data-target="#confirmDelete"
data-title="Delete Something"
data-message="Are you sure you want to inactivate this something?"
data-url="client/32"
id="delete-client-32">
</a>
<!-- jQuery should come before this -->
<%@ include file="../some/path/confirmDelete.jsp" %>
참고: 삭제 요청에는 http delete 방법을 사용하며, javascript에서 변경하거나, data-title 또는 data-url 등과 같이 데이터 속성을 사용하여 요청을 전송할 수 있습니다.
가장 쉬운 바로 가기를 원한다면 이 플러그인으로 할 수 있습니다.
그러나 이 플러그인은 부트스트랩 모달을 사용하는 대체 구현입니다.그리고 실제 부트스트랩 구현도 매우 쉬워서 이 플러그인은 페이지에 JS 콘텐츠가 과도하게 추가되어 페이지 로딩 시간이 느려지기 때문에 사용하고 싶지 않습니다.
아이디어
이런 식으로 혼자서 실행하는 것을 좋아합니다.
- 사용자가 버튼을 클릭하여 목록에서 항목을 삭제하면 JS 호출은 항목 ID(또는 더 중요한 데이터)를 모달의 양식에 저장합니다.
그러면 팝업에 확인 버튼이 2개 있습니다.
- 예, 양식 제출(Ajax 또는 직접 양식 제출 포함)
- 아니오는 모달을 그냥 무시할 것입니다.
코드는 다음과 같습니다(부트스트랩 사용)-
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
$(document).ready(function()
{
$("button").click(function()
{
//Say - $('p').get(0).id - this delete item id
$("#delete_item_id").val( $('p').get(0).id );
$('#delete_confirmation_modal').modal('show');
});
});
</script>
<p id="1">This is a item to delete.</p>
<button type="button" class="btn btn-danger">Delete</button>
<!-- Delete Modal content-->
<div class="modal fade" id="delete_confirmation_modal" role="dialog" style="display: none;">
<div class="modal-dialog" style="margin-top: 260.5px;">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Do you really want to delete this Category?</h4>
</div>
<form role="form" method="post" action="category_delete" id="delete_data">
<input type="hidden" id="delete_item_id" name="id" value="12">
<div class="modal-footer">
<button type="submit" class="btn btn-danger">Yes</button>
<button type="button" class="btn btn-primary" data-dismiss="modal">No</button>
</div>
</form>
</div>
</div>
</div>
요구 사항에 따라 양식 작업을 변경해야 합니다.
해피 코딩 :)
콜백 기능이 있는 재사용 가능한 내 솔루션을 사용해 볼 수 있습니다.이 기능에서는 POST 요청 또는 일부 로직을 사용할 수 있습니다.사용된 라이브러리: JQuery 3> 및 Bootstrap 3>.
https://jsfiddle.net/axnikitenko/gazbyv8v/
테스트용 HTML 코드:
...
<body>
<a href='#' id="remove-btn-a-id" class="btn btn-default">Test Remove Action</a>
</body>
...
Javascript:
$(function () {
function remove() {
alert('Remove Action Start!');
}
// Example of initializing component data
this.cmpModalRemove = new ModalConfirmationComponent('remove-data', remove,
'remove-btn-a-id', {
txtModalHeader: 'Header Text For Remove', txtModalBody: 'Body For Text Remove',
txtBtnConfirm: 'Confirm', txtBtnCancel: 'Cancel'
});
this.cmpModalRemove.initialize();
});
//----------------------------------------------------------------------------------------------------------------------
// COMPONENT SCRIPT
//----------------------------------------------------------------------------------------------------------------------
/**
* Script processing data for confirmation dialog.
* Used libraries: JQuery 3> and Bootstrap 3>.
*
* @param name unique component name at page scope
* @param callback function which processing confirm click
* @param actionBtnId button for open modal dialog
* @param text localization data, structure:
* > txtModalHeader - text at header of modal dialog
* > txtModalBody - text at body of modal dialog
* > txtBtnConfirm - text at button for confirm action
* > txtBtnCancel - text at button for cancel action
*
* @constructor
* @author Aleksey Nikitenko
*/
function ModalConfirmationComponent(name, callback, actionBtnId, text) {
this.name = name;
this.callback = callback;
// Text data
this.txtModalHeader = text.txtModalHeader;
this.txtModalBody = text.txtModalBody;
this.txtBtnConfirm = text.txtBtnConfirm;
this.txtBtnCancel = text.txtBtnCancel;
// Elements
this.elmActionBtn = $('#' + actionBtnId);
this.elmModalDiv = undefined;
this.elmConfirmBtn = undefined;
}
/**
* Initialize needed data for current component object.
* Generate html code and assign actions for needed UI
* elements.
*/
ModalConfirmationComponent.prototype.initialize = function () {
// Generate modal html and assign with action button
$('body').append(this.getHtmlModal());
this.elmActionBtn.attr('data-toggle', 'modal');
this.elmActionBtn.attr('data-target', '#'+this.getModalDivId());
// Initialize needed elements
this.elmModalDiv = $('#'+this.getModalDivId());
this.elmConfirmBtn = $('#'+this.getConfirmBtnId());
// Assign click function for confirm button
var object = this;
this.elmConfirmBtn.click(function() {
object.elmModalDiv.modal('toggle'); // hide modal
object.callback(); // run callback function
});
};
//----------------------------------------------------------------------------------------------------------------------
// HTML GENERATORS
//----------------------------------------------------------------------------------------------------------------------
/**
* Methods needed for get html code of modal div.
*
* @returns {string} html code
*/
ModalConfirmationComponent.prototype.getHtmlModal = function () {
var result = '<div class="modal fade" id="' + this.getModalDivId() + '"';
result +=' tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">';
result += '<div class="modal-dialog"><div class="modal-content"><div class="modal-header">';
result += this.txtModalHeader + '</div><div class="modal-body">' + this.txtModalBody + '</div>';
result += '<div class="modal-footer">';
result += '<button type="button" class="btn btn-default" data-dismiss="modal">';
result += this.txtBtnCancel + '</button>';
result += '<button id="'+this.getConfirmBtnId()+'" type="button" class="btn btn-danger">';
result += this.txtBtnConfirm + '</button>';
return result+'</div></div></div></div>';
};
//----------------------------------------------------------------------------------------------------------------------
// UTILITY
//----------------------------------------------------------------------------------------------------------------------
/**
* Get id element with name prefix for this component.
*
* @returns {string} element id
*/
ModalConfirmationComponent.prototype.getModalDivId = function () {
return this.name + '-modal-id';
};
/**
* Get id element with name prefix for this component.
*
* @returns {string} element id
*/
ModalConfirmationComponent.prototype.getConfirmBtnId = function () {
return this.name + '-confirm-btn-id';
};
대상 페이지로 이동하는 POST Recipe 및 재사용 가능한 Blade 파일
dfsq의 대답은 매우 좋습니다.필요에 맞게 약간 수정했습니다.저는 실제로 클릭 후 사용자가 해당 페이지로 이동하는 경우를 위한 모달이 필요했습니다.쿼리를 비동기식으로 실행하는 것이 항상 필요한 것은 아닙니다.
사용.Blade
파일을 만들었습니다.resources/views/includes/confirmation_modal.blade.php
:
<div class="modal fade" id="confirmation-modal" tabindex="-1" role="dialog" aria-labelledby="confirmation-modal-label" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4>{{ $headerText }}</h4>
</div>
<div class="modal-body">
{{ $bodyText }}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<form action="" method="POST" style="display:inline">
{{ method_field($verb) }}
{{ csrf_field() }}
<input type="submit" class="btn btn-danger btn-ok" value="{{ $confirmButtonText }}" />
</form>
</div>
</div>
</div>
</div>
<script>
$('#confirmation-modal').on('show.bs.modal', function(e) {
href = $(e.relatedTarget).data('href');
// change href of button to corresponding target
$(this).find('form').attr('action', href);
});
</script>
이제 사용 방법은 간단합니다.
<a data-href="{{ route('data.destroy', ['id' => $data->id]) }}" data-toggle="modal" data-target="#confirmation-modal" class="btn btn-sm btn-danger">Remove</a>
여기에서는 크게 변경되지 않았으며 모달은 다음과 같이 포함될 수 있습니다.
@include('includes.confirmation_modal', ['headerText' => 'Delete Data?', 'bodyText' => 'Do you really want to delete these data? This operation is irreversible.',
'confirmButtonText' => 'Remove Data', 'verb' => 'DELETE'])
동사를 거기에 넣는 것만으로도, 그것은 그것을 사용합니다.이러한 방식으로 CSRF도 사용됩니다.
도움이 됐어요, 다른 사람에게 도움이 될 수도 있어요.
부트스트랩에 대한 확인 상자 "jquery component"입니다. 코드에 이것을 사용하십시오.
function ConfirmBox({title,message,result}){
let confirm = $(`
<div class="modal fade" tabindex="-1" id="confirmBox" role="dialog" aria-labelledby="modalLabelSmall" aria-hidden="true">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header" style="text-align:center">
<button type="button" class="close" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="modalLabelSmall">${title}</h4>
</div>
<div class="modal-body">
${message}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default confirmButton">sure</button>
</div>
</div>
</div>
</div>
`);
//append confirm box to the DOM
$("body").append(confirm);
confirm.modal();
//handlers
confirm.find("button.confirmButton").one("click",function(){
result(true);
confirm.modal("hide");
});
confirm.find("button.close").one("click",function(){
result(false);
confirm.modal("hide");
})
//remove modal after hiding it
confirm.one('hidden.bs.modal', function () {
confirm.remove();
});
}
언급URL : https://stackoverflow.com/questions/8982295/confirm-deletion-in-modal-dialog-using-twitter-bootstrap
'programing' 카테고리의 다른 글
시스템과 함께 HTTP POST를 보내는 중입니다.Net.WebClient (0) | 2023.05.14 |
---|---|
Azure 가용성 세트 및 척도 세트의 차이 (0) | 2023.05.14 |
플라스크 사용자 인증 (0) | 2023.05.14 |
주피터 노트북을 사용할 때 "실행 중인 이벤트 루프에서 asyncio.run()을 호출할 수 없음" (0) | 2023.05.14 |
일반 PropertyMetadata보다 FrameworkPropertyMetadata 또는 UIPPropertyMetadata를 언제 사용해야 합니까? (0) | 2023.05.09 |