使用Bootstrap 3模态框确认删除

60

我需要使用Bootstrap 3模态框(是/否)来确认删除。我该如何创建?

HTML代码:

<form action="blah" method="POST">
    <button class='btn' type="submit" name="remove_levels" value="delete">
        <span class="fa fa-times"></span> Delete
    </button>
</form>

https://dev59.com/aGox5IYBdhLWcg3ww3GV#42346781 - Alexey Nikitenko
9个回答

98

你需要在HTML中使用模态框。当单击删除按钮时,它会弹出模态框。还很重要的是要防止该按钮的点击提交表单。当确认被点击时,表单将被提交。

   

 $('button[name="remove_levels"]').on('click', function(e) {
      var $form = $(this).closest('form');
      e.preventDefault();
      $('#confirm').modal({
          backdrop: 'static',
          keyboard: false
      })
      .on('click', '#delete', function(e) {
          $form.trigger('submit');
        });
      $("#cancel").on('click',function(e){
       e.preventDefault();
       $('#confirm').modal.model('hide');
      });
    });
<link href="http://getbootstrap.com/2.3.2/assets/css/bootstrap.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://getbootstrap.com/2.3.2/assets/js/bootstrap.js"></script>
<form action="#" method="POST">
  <button class='btn btn-danger btn-xs' type="submit" name="remove_levels" value="delete"><span class="fa fa-times"></span> delete</button>
</form>

<div id="confirm" class="modal">
  <div class="modal-body">
    Are you sure?
  </div>
  <div class="modal-footer">
    <button type="button" data-dismiss="modal" class="btn btn-primary" id="delete">Delete</button>
    <button type="button" data-dismiss="modal" class="btn">Cancel</button>
  </div>
</div>


3
这个很好用,但有一个需要注意的地方:如果我先点击取消,再点击删除,然后再次点击删除,在我的情况下,提交会被发送两次。它应该只提交一次。 - Khrys
2
@Khrys,你应该验证是否包含了 e.preventDefault() - Nathan Koop
1
这里有一个问题。请注意,如果您正在使用此功能来确认删除某个带有ID的内容。问题在于,如果您点击“取消”,事件仍将附加到模态框上。如果您之后再点击另一个要删除的内容,它将同时删除两个。 - Pedro Lourenço
1
针对之前评论中提到的问题,Pedro指出$('#confirm').unbind()可以帮助解除绑定的事件。 - shivg
@NigelAngel 如果我点击“取消”按钮的次数为n,则.one('click', '#delete', function(e) {})调用n次。如果我在前三次点击“取消”按钮,然后点击“删除”按钮,我的.one({})会执行4次。请检查。 - Chinmay235
显示剩余2条评论

18
您可以使用Bootbox对话框。
$(document).ready(function() {

  $('#btnDelete').click(function() {
    bootbox.confirm("Are you sure want to delete?", function(result) {
      alert("Confirm result: " + result);
    });
  });
});

Plunker演示


3
注意,bootbox 可能会与 bootstrap 模态框发生冲突。抱歉回答这个老问题,但我刚遇到了这个问题。 - SuperManSL

12

今天我遇到了同样的问题。这是我的解决方案(我认为更好更简单):

<!-- Modal dialog -->
<div class="modal fade" id="frmPrenotazione" tabindex="-1">
    <!-- CUTTED -->
    <div id="step1" class="modal-footer">
      <button type="button" class="glyphicon glyphicon-erase btn btn-default" id="btnDelete"> Delete</button>
    </div>
</div>

<!-- Modal confirm -->
<div class="modal" id="confirmModal" style="display: none; z-index: 1050;">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-body" id="confirmMessage">
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" id="confirmOk">Ok</button>
                <button type="button" class="btn btn-default" id="confirmCancel">Cancel</button>
            </div>
        </div>
    </div>
</div>

在我的 .js 文件中:

$('#btnDelete').on('click', function(e){
    confirmDialog(YOUR_MESSAGE_STRING_CONST, function(){
        //My code to delete
    });
});

function confirmDialog(message, onConfirm){
    var fClose = function(){
        modal.modal("hide");
    };
    var modal = $("#confirmModal");
    modal.modal("show");
    $("#confirmMessage").empty().append(message);
    $("#confirmOk").unbind().one('click', onConfirm).one('click', fClose);
    $("#confirmCancel").unbind().one("click", fClose);
}

在使用 one 函数之前,使用 unbind 函数可以防止下次打开对话框时调用删除函数。

我希望这能有所帮助。

以下是一个完整的示例:

var YOUR_MESSAGE_STRING_CONST = "Your confirm message?";
      $('#btnDelete').on('click', function(e){
      confirmDialog(YOUR_MESSAGE_STRING_CONST, function(){
       //My code to delete
          console.log("deleted!");
      });
     });

        function confirmDialog(message, onConfirm){
         var fClose = function(){
         modal.modal("hide");
         };
         var modal = $("#confirmModal");
         modal.modal("show");
         $("#confirmMessage").empty().append(message);
         $("#confirmOk").unbind().one('click', onConfirm).one('click', fClose);
         $("#confirmCancel").unbind().one("click", fClose);
        }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<!-- Modal dialog -->
<div id="frmTest" tabindex="-1">
    <!-- CUTTED -->
      <div id="step1" class="modal-footer">
    <button type="button" class="glyphicon glyphicon-erase btn btn-default" id="btnDelete"> Delete</button>
  </div>
</div>

  <!-- Modal confirm -->
<div class="modal" id="confirmModal" style="display: none; z-index: 1050;">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-body" id="confirmMessage">
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" id="confirmOk">Ok</button>
            <button type="button" class="btn btn-default" id="confirmCancel">Cancel</button>
          </div>
    </div>
  </div>
</div>


6

使用模态框的简单方法是使用eModal

来自github的示例:

  1. 链接到eModal.js <script src="//rawgit.com/saribe/eModal/master/dist/eModal.min.js"></script>

    var options = {
            message: "The famouse question?",
            title: 'Header title',
            size: 'sm',
            callback: function(result) { result ? doActionTrue(result) :    doActionFalse(); },
            subtitle: 'smaller text header',
            label: "True"   // use the possitive lable as key
            //...
        };
                     
    eModal.confirm(options);
 <link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.1/js/bootstrap.min.js"></script>
<script src="//rawgit.com/saribe/eModal/master/dist/eModal.min.js"></script>

提示:您可以更改默认标签名称!{ label: '是' | '真' | '确定' }


4
$('.launchConfirm').on('click', function (e) {
    $('#confirm')
        .modal({ backdrop: 'static', keyboard: false })
        .one('click', '#delete', function (e) {
            //delete function
        });
});

点击此处查看按钮效果:

对于你的按钮:

<button class='btn btn-danger btn-xs launchConfirm' type="button" name="remove_levels"><span class="fa fa-times"></span> delete</button></td>

这不是在给定代码的上下文中。OP如何将其应用于他/她的代码? - Popnoodles

2
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
  Launch demo modal
</button>

<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

https://getbootstrap.com/docs/4.0/components/modal/


1

使用id="confirmation"在HTML中创建模态对话框,并使用showConfirmation函数。

同时请记住,在隐藏模态对话框后,您应该取消绑定(cancel和success按钮)。如果您不这样做,将会出现双重绑定的情况。 例如:如果您打开对话框一次,按下“取消”,然后再次打开对话框并按下“确定”,您将获得两个成功回调的执行。

showConfirmation = function(title, message, success, cancel) {
    title = title ? title : 'Are you sure?';
    var modal = $("#confirmation");
    modal.find(".modal-title").html(title).end()
        .find(".modal-body").html(message).end()
        .modal({ backdrop: 'static', keyboard: false })
        .on('hidden.bs.modal', function () {
            modal.unbind();
        });
    if (success) {
        modal.one('click', '.modal-footer .btn-primary', success);
    }
    if (cancel) {
        modal.one('click', '.modal-header .close, .modal-footer .btn-default', cancel);
    }
};

// bind confirmation dialog on delete buttons
$(document).on("click", ".delete-event, .delete-all-event", function(event){
    event.preventDefault();
    var self = $(this);
    var url = $(this).data('url');
    var success = function(){
        alert('window.location.href=url');
    }
    var cancel = function(){
        alert('Cancel');
    };
    if (self.data('confirmation')) {
        var title = self.data('confirmation-title') ? self.data('confirmation-title') : undefined;
        var message = self.data('confirmation');
        showConfirmation(title, message, success, cancel);
    } else {
        success();
    }
});

https://jsfiddle.net/yiiBoy/hne9sp6g/


0

$('button[name="remove_levels"]').on('click', function(e) {
  var $form = $(this).closest('form');
    e.preventDefault();
    $('#confirm').modal({
    backdrop: 'static',
    keyboard: false
  })
  .on('click', '#delete', function(e) {
    $form.trigger('submit');
  });
  $("#cancel").on('click',function(e){
    e.preventDefault();
    $('#confirm').modal.model('hide');
  });
});
<link href="http://getbootstrap.com/2.3.2/assets/css/bootstrap.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://getbootstrap.com/2.3.2/assets/js/bootstrap.js"></script>

<form action="#" method="POST">
  <button class='btn btn-danger btn-xs' type="submit" name="remove_levels" value="delete"><span class="fa fa-times"></span> delete</button>
</form>
<div id="confirm" class="modal">
  <div class="modal-body">
    Are you sure?
  </div>
  <div class="modal-footer">
    <button type="button" data-dismiss="modal" class="btn btn-primary" id="delete">Delete</button>
    <button type="button" data-dismiss="modal" class="btn">Cancel</button>
  </div>
</div>

这段代码无法正常工作,需要进行以下更改:

  1. 需要在取消按钮上定义id="cancel"

     <button type="button" data-dismiss="modal" id="cancel" class="btn">取消</button>
    
  2. 取消点击事件更改如下

     $('button[name="remove_levels"]').on('click', function(e) {
       var $form = $(this).closest('form');
       e.preventDefault();
       $('#confirm').modal({
           backdrop: 'static',
           keyboard: false
       })
       .on('click', '#delete', function(e) {
           $form.trigger('submit');
         })
       .on('click','#cancel', function(e){
        e.preventDefault();
        $('#confirm').modal.model('hide');
       });
     });
    

-1

在此输入图像描述 以下解决方案比bootbox.js更好,因为:

  • 它可以做到bootbox.js所能做的一切;
  • 使用语法更简单;
  • 它允许您通过“error”、“warning”或“info”优雅地控制消息的颜色;
  • 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');
}

使用 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>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接