I have an HTML table of rows tied to database rows. I'd like to have a "delete row" link for each row, but I would like to confirm with the user beforehand.
我有一个绑定到数据库行的HTML表行。我希望每行都有一个“删除行”链接,但我想事先与用户确认。
Is there any way to do this using the Twitter Bootstrap modal dialog?
有没有办法使用Twitter Bootstrap模式对话框?
12 个解决方案
#1
349
GET recipe
For this task you can use already available plugins and bootstrap extensions. Or you can make your own confirmation popup with just 3 lines of code. Check it out.
对于此任务,您可以使用已有的插件和引导扩展。或者,您只需3行代码即可创建自己的确认弹出窗口。一探究竟。
Say we have this links (note data-href
instead of href
) or buttons that we want to have delete confirmation for:
假设我们有这个链接(注意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>
Here #confirm-delete
points to a modal popup div in your HTML. It should have an "OK" button configured like this:
这里#confirm-delete指向HTML中的模式弹出div。它应该有一个“OK”按钮配置如下:
<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>
Now you only need this little javascript to make a delete action confirmable:
现在你只需要这个小javascript来确认删除操作:
$('#confirm-delete').on('show.bs.modal', function(e) {
$(this).find('.btn-ok').attr('href', $(e.relatedTarget).data('href'));
});
So on show.bs.modal
event delete button href
is set to URL with corresponding record id.
所以在show.bs.modal事件中,删除按钮href被设置为具有相应记录id的URL。
Demo: http://plnkr.co/edit/NePR0BQf3VmKtuMmhVR7?p=preview
POST recipe
I realize that in some cases there might be needed to perform POST or DELETE request rather then GET. It it still pretty simple without too much code. Take a look at the demo below with this approach:
我意识到在某些情况下可能需要执行POST或DELETE请求而不是GET。没有太多代码,它仍然非常简单。使用以下方法查看下面的演示:
// 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>
Demo: http://plnkr.co/edit/V4GUuSueuuxiGr4L9LmG?p=preview
Bootstrap 2.3
Here is an original version of the code I made when I was answering this question for Bootstrap 2.3 modal.
这是我在回答Bootstrap 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));
});
#2
153
http://bootboxjs.com/ - latest works with Bootstrap 3.0.0
http://bootboxjs.com/ - 最新版本与Bootstrap 3.0.0一起使用
The simplest possible example:
最简单的例子:
bootbox.alert("Hello world!");
From the site:
从网站:
The library exposes three methods designed to mimic their native JavaScript equivalents. Their exact method signatures are flexible as each can take various parameters to customise labels and specify defaults, but they are most commonly called like so:
该库公开了三种旨在模仿其原生JavaScript等价物的方法。他们的确切方法签名是灵活的,因为每个都可以采用各种参数来自定义标签和指定默认值,但它们通常被称为如下:
bootbox.alert(message, callback)
bootbox.prompt(message, callback)
bootbox.confirm(message, callback)
Here's a snippet of it in action (click "Run code snippet" below):
这是一个实际的片段(点击下面的“运行代码片段”):
$(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>
#3
31
// ---------------------------------------------------------- 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);
});
#4
27
I'd realise its a very old question, but since i wondered today for a more efficient method of handling the bootstrap modals. I did some research and found something better then the solutions which are shown above, that can be found at this link:
我意识到这是一个非常古老的问题,但是因为我今天想知道一个更有效的方法来处理引导模态。我做了一些研究,发现了比上面显示的解决方案更好的东西,可以在这个链接找到:
http://www.petefreitag.com/item/809.cfm
First load the jquery
首先加载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;
});
});
Then just ask any question/confirmation to href:
然后只要问任何问题/确认href:
<a href="/any/url/delete.php?ref=ID" data-confirm="Are you sure you want to delete?">Delete</a>
This way the confirmation modal is a lot more universal and so it can easily be re-used on other parts of your website.
这样,确认模式更具通用性,因此可以轻松地在网站的其他部分重复使用。
#5
15
Thanks to @Jousby's solution, I managed to get mine working as well, but found I had to improve his solution's Bootstrap modal markup a bit to make it render correctly as demonstrated in the official examples.
感谢@ Jousby的解决方案,我设法让我的工作也工作,但发现我必须改进他的解决方案的Bootstrap模态标记,以使其正确渲染,如官方示例中所示。
So, here's my modified version of the generic confirm
function that worked fine:
所以,这是我的通用确认函数的修改版本,运行正常:
/* 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 */
#6
7
I found this useful and easy to use, plus it looks pretty: http://maxailloud.github.io/confirm-bootstrap/.
我觉得这很有用且易于使用,而且它看起来很漂亮:http://maxailloud.github.io/confirm-bootstrap/。
To use it, include the .js file in your page then run:
要使用它,请在页面中包含.js文件,然后运行:
$('your-link-selector').confirmModal();
There are various options you can apply to it, to make it look better when doing it to confirm a delete, I use:
您可以应用各种选项,以便在确认删除时使其看起来更好,我使用:
$('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..
}
});
#7
3
I can easily handle this type of task using bootbox.js library. At first you need to include bootbox JS file. Then in your event handler function simply write following code:
我可以使用bootbox.js库轻松处理这种类型的任务。首先,您需要包含bootbox JS文件。然后在您的事件处理函数中,只需编写以下代码:
bootbox.confirm("Are you sure to want to delete , function(result) {
//here result will be true
// delete process code goes here
});
Offical bootboxjs site
官方bootboxjs网站
#8
2
Following solution is better than bootbox.js, because
以下解决方案比bootbox.js更好,因为
- It can do everything bootbox.js can do;
- The use syntax is simpler
- It allows you to elegantly control the color of your message using "error", "warning" or "info"
- Bootbox is 986 lines long, mine only 110 lines long
它可以做bootbox.js可以做的一切;
使用语法更简单
它允许您使用“错误”,“警告”或“信息”优雅地控制邮件的颜色
Bootbox长986线,我的线只有110线
digimango.messagebox.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');
}
To use digimango.messagebox.js:
要使用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>
#9
1
You can try more reusable my solution with callback function. In this function you can use POST request or some logic. Used libraries: JQuery 3> and Bootstrap 3>.
您可以使用回调函数尝试更多可重用的解决方案。在此功能中,您可以使用POST请求或某些逻辑。使用过的库:JQuery 3>和Bootstrap 3>。
https://jsfiddle.net/axnikitenko/gazbyv8v/
Html code for test:
用于测试的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';
};
#10
0
When its comes to a relevantly big project we may need something re-usable. This is something I came with with help of SO.
当它涉及一个相关的大项目时,我们可能需要一些可重复使用的东西。这是我在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/>
reusingPage.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" %>
Note: This uses http delete method for delete request, you can change it from javascript or, can send it using a data-attribute as in data-title or data-url etc, for support any request.
注意:这对删除请求使用http delete方法,您可以从javascript更改它,或者可以使用data-title或data-url等数据属性发送它,以支持任何请求。
#11
0
If you want to do it in the easiest shortcut, then u can do it with this plugin.
如果你想用最简单的快捷方式来做,那么你可以用这个插件做到这一点。
But this plugin is an alternate implementation using Bootstrap Modal. And real Bootstrap implementation is also very easy, so I don't like to use this plugin because it adds excess JS contents in the page, which will slow down the page loading time.
但是这个插件是使用Bootstrap Modal的替代实现。真正的Bootstrap实现也非常简单,所以我不喜欢使用这个插件,因为它在页面中添加了多余的JS内容,这将减慢页面加载时间。
Idea
I like to implement it by myself by this way-
我喜欢以这种方式自己实施 -
- If user clicks on a button to delete an item from the list, then a JS call will put Item ID (or any more essential data) in a form in the modal.
-
Then in the pop-up, there will be 2 buttons for confirmation.
然后在弹出窗口中,将有2个按钮用于确认。
- Yes will submit the form (with ajax or direct form submit)
- No will just dismiss the modal
是的将提交表格(使用ajax或直接表格提交)
不会只是解雇模态
如果用户单击按钮从列表中删除项目,则JS调用会将项目ID(或任何更重要的数据)放入模式中的表单中。
The code will be like this (using Bootstrap)-
代码将是这样的(使用Bootstrap) -
<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>
You should change the form action according to your requirement.
您应该根据您的要求更改表单操作。
Happy coading :)
快乐的coading :)
#12
0
POST Recipe with navigation to target page and reusable Blade file
dfsq's answer is very nice. I modified it a bit to fit my needs: I actually needed a modal for the case that, after clicking, the user would also be navigated to the corresponding page. Executing the query asynchronously is not always what one needs.
dfsq的答案非常好。我修改了一下以满足我的需要:我实际上需要一个模态,在点击后,用户也会被导航到相应的页面。异步执行查询并不总是需要的。
Using Blade
I created the file resources/views/includes/confirmation_modal.blade.php
:
使用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>
Now, using it is straight-forward:
现在,使用它是直截了当的:
<a data-href="{{ route('data.destroy', ['id' => $data->id]) }}" data-toggle="modal" data-target="#confirmation-modal" class="btn btn-sm btn-danger">Remove</a>
Not much changed here and the modal can be included like this:
这里没有太大的改变,模态可以像这样包括:
@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'])
Just by putting the verb in there, it uses it. This way, CSRF is also utilized.
只需将动词放在那里,它就会使用它。这样,CSRF也被利用。
Helped me, maybe it helps someone else.
帮帮我,也许它可以帮助别人。
#1
349
GET recipe
For this task you can use already available plugins and bootstrap extensions. Or you can make your own confirmation popup with just 3 lines of code. Check it out.
对于此任务,您可以使用已有的插件和引导扩展。或者,您只需3行代码即可创建自己的确认弹出窗口。一探究竟。
Say we have this links (note data-href
instead of href
) or buttons that we want to have delete confirmation for:
假设我们有这个链接(注意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>
Here #confirm-delete
points to a modal popup div in your HTML. It should have an "OK" button configured like this:
这里#confirm-delete指向HTML中的模式弹出div。它应该有一个“OK”按钮配置如下:
<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>
Now you only need this little javascript to make a delete action confirmable:
现在你只需要这个小javascript来确认删除操作:
$('#confirm-delete').on('show.bs.modal', function(e) {
$(this).find('.btn-ok').attr('href', $(e.relatedTarget).data('href'));
});
So on show.bs.modal
event delete button href
is set to URL with corresponding record id.
所以在show.bs.modal事件中,删除按钮href被设置为具有相应记录id的URL。
Demo: http://plnkr.co/edit/NePR0BQf3VmKtuMmhVR7?p=preview
POST recipe
I realize that in some cases there might be needed to perform POST or DELETE request rather then GET. It it still pretty simple without too much code. Take a look at the demo below with this approach:
我意识到在某些情况下可能需要执行POST或DELETE请求而不是GET。没有太多代码,它仍然非常简单。使用以下方法查看下面的演示:
// 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>
Demo: http://plnkr.co/edit/V4GUuSueuuxiGr4L9LmG?p=preview
Bootstrap 2.3
Here is an original version of the code I made when I was answering this question for Bootstrap 2.3 modal.
这是我在回答Bootstrap 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));
});
#2
153
http://bootboxjs.com/ - latest works with Bootstrap 3.0.0
http://bootboxjs.com/ - 最新版本与Bootstrap 3.0.0一起使用
The simplest possible example:
最简单的例子:
bootbox.alert("Hello world!");
From the site:
从网站:
The library exposes three methods designed to mimic their native JavaScript equivalents. Their exact method signatures are flexible as each can take various parameters to customise labels and specify defaults, but they are most commonly called like so:
该库公开了三种旨在模仿其原生JavaScript等价物的方法。他们的确切方法签名是灵活的,因为每个都可以采用各种参数来自定义标签和指定默认值,但它们通常被称为如下:
bootbox.alert(message, callback)
bootbox.prompt(message, callback)
bootbox.confirm(message, callback)
Here's a snippet of it in action (click "Run code snippet" below):
这是一个实际的片段(点击下面的“运行代码片段”):
$(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>
#3
31
// ---------------------------------------------------------- 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);
});
#4
27
I'd realise its a very old question, but since i wondered today for a more efficient method of handling the bootstrap modals. I did some research and found something better then the solutions which are shown above, that can be found at this link:
我意识到这是一个非常古老的问题,但是因为我今天想知道一个更有效的方法来处理引导模态。我做了一些研究,发现了比上面显示的解决方案更好的东西,可以在这个链接找到:
http://www.petefreitag.com/item/809.cfm
First load the jquery
首先加载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;
});
});
Then just ask any question/confirmation to href:
然后只要问任何问题/确认href:
<a href="/any/url/delete.php?ref=ID" data-confirm="Are you sure you want to delete?">Delete</a>
This way the confirmation modal is a lot more universal and so it can easily be re-used on other parts of your website.
这样,确认模式更具通用性,因此可以轻松地在网站的其他部分重复使用。
#5
15
Thanks to @Jousby's solution, I managed to get mine working as well, but found I had to improve his solution's Bootstrap modal markup a bit to make it render correctly as demonstrated in the official examples.
感谢@ Jousby的解决方案,我设法让我的工作也工作,但发现我必须改进他的解决方案的Bootstrap模态标记,以使其正确渲染,如官方示例中所示。
So, here's my modified version of the generic confirm
function that worked fine:
所以,这是我的通用确认函数的修改版本,运行正常:
/* 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 */
#6
7
I found this useful and easy to use, plus it looks pretty: http://maxailloud.github.io/confirm-bootstrap/.
我觉得这很有用且易于使用,而且它看起来很漂亮:http://maxailloud.github.io/confirm-bootstrap/。
To use it, include the .js file in your page then run:
要使用它,请在页面中包含.js文件,然后运行:
$('your-link-selector').confirmModal();
There are various options you can apply to it, to make it look better when doing it to confirm a delete, I use:
您可以应用各种选项,以便在确认删除时使其看起来更好,我使用:
$('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..
}
});
#7
3
I can easily handle this type of task using bootbox.js library. At first you need to include bootbox JS file. Then in your event handler function simply write following code:
我可以使用bootbox.js库轻松处理这种类型的任务。首先,您需要包含bootbox JS文件。然后在您的事件处理函数中,只需编写以下代码:
bootbox.confirm("Are you sure to want to delete , function(result) {
//here result will be true
// delete process code goes here
});
Offical bootboxjs site
官方bootboxjs网站
#8
2
Following solution is better than bootbox.js, because
以下解决方案比bootbox.js更好,因为
- It can do everything bootbox.js can do;
- The use syntax is simpler
- It allows you to elegantly control the color of your message using "error", "warning" or "info"
- Bootbox is 986 lines long, mine only 110 lines long
它可以做bootbox.js可以做的一切;
使用语法更简单
它允许您使用“错误”,“警告”或“信息”优雅地控制邮件的颜色
Bootbox长986线,我的线只有110线
digimango.messagebox.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');
}
To use digimango.messagebox.js:
要使用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>
#9
1
You can try more reusable my solution with callback function. In this function you can use POST request or some logic. Used libraries: JQuery 3> and Bootstrap 3>.
您可以使用回调函数尝试更多可重用的解决方案。在此功能中,您可以使用POST请求或某些逻辑。使用过的库:JQuery 3>和Bootstrap 3>。
https://jsfiddle.net/axnikitenko/gazbyv8v/
Html code for test:
用于测试的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';
};
#10
0
When its comes to a relevantly big project we may need something re-usable. This is something I came with with help of SO.
当它涉及一个相关的大项目时,我们可能需要一些可重复使用的东西。这是我在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/>
reusingPage.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" %>
Note: This uses http delete method for delete request, you can change it from javascript or, can send it using a data-attribute as in data-title or data-url etc, for support any request.
注意:这对删除请求使用http delete方法,您可以从javascript更改它,或者可以使用data-title或data-url等数据属性发送它,以支持任何请求。
#11
0
If you want to do it in the easiest shortcut, then u can do it with this plugin.
如果你想用最简单的快捷方式来做,那么你可以用这个插件做到这一点。
But this plugin is an alternate implementation using Bootstrap Modal. And real Bootstrap implementation is also very easy, so I don't like to use this plugin because it adds excess JS contents in the page, which will slow down the page loading time.
但是这个插件是使用Bootstrap Modal的替代实现。真正的Bootstrap实现也非常简单,所以我不喜欢使用这个插件,因为它在页面中添加了多余的JS内容,这将减慢页面加载时间。
Idea
I like to implement it by myself by this way-
我喜欢以这种方式自己实施 -
- If user clicks on a button to delete an item from the list, then a JS call will put Item ID (or any more essential data) in a form in the modal.
-
Then in the pop-up, there will be 2 buttons for confirmation.
然后在弹出窗口中,将有2个按钮用于确认。
- Yes will submit the form (with ajax or direct form submit)
- No will just dismiss the modal
是的将提交表格(使用ajax或直接表格提交)
不会只是解雇模态
如果用户单击按钮从列表中删除项目,则JS调用会将项目ID(或任何更重要的数据)放入模式中的表单中。
The code will be like this (using Bootstrap)-
代码将是这样的(使用Bootstrap) -
<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>
You should change the form action according to your requirement.
您应该根据您的要求更改表单操作。
Happy coading :)
快乐的coading :)
#12
0
POST Recipe with navigation to target page and reusable Blade file
dfsq's answer is very nice. I modified it a bit to fit my needs: I actually needed a modal for the case that, after clicking, the user would also be navigated to the corresponding page. Executing the query asynchronously is not always what one needs.
dfsq的答案非常好。我修改了一下以满足我的需要:我实际上需要一个模态,在点击后,用户也会被导航到相应的页面。异步执行查询并不总是需要的。
Using Blade
I created the file resources/views/includes/confirmation_modal.blade.php
:
使用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>
Now, using it is straight-forward:
现在,使用它是直截了当的:
<a data-href="{{ route('data.destroy', ['id' => $data->id]) }}" data-toggle="modal" data-target="#confirmation-modal" class="btn btn-sm btn-danger">Remove</a>
Not much changed here and the modal can be included like this:
这里没有太大的改变,模态可以像这样包括:
@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'])
Just by putting the verb in there, it uses it. This way, CSRF is also utilized.
只需将动词放在那里,它就会使用它。这样,CSRF也被利用。
Helped me, maybe it helps someone else.
帮帮我,也许它可以帮助别人。