60

I need to confirm deletion using Bootstrap 3 modal box (YES/NO). How can I create this?

HTML code:

<form action="blah" method="POST">
    <button class='btn' type="submit" name="remove_levels" value="delete">
        <span class="fa fa-times"></span> Delete
    </button>
</form>
isherwood
  • 58,414
  • 16
  • 114
  • 157
Pink Code
  • 1,802
  • 7
  • 43
  • 65

8 Answers8

98

You need the modal in your HTML. When the delete button is clicked it popup the modal. It's also important to prevent the click of that button from submitting the form. When the confirmation is clicked the form will submit.

   

 $('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>
Mayank chauhan
  • 378
  • 4
  • 10
  • 3
    This works great, with one side note: If I click in delete, after If I click in cancel, then I click in delete again, in my case scenario, the submit is sent 2 times. It should submit only one. – Khrys Dec 04 '14 at 18:21
  • 2
    @Khrys, you should verify that you have included `e.prevenDefault()` – Nathan Koop Dec 19 '14 at 20:49
  • 1
    There's a problem here. Take notice that if you are using this to confirm delete something with some kind of ID. What happens is, if you click "Cancel" the event will still be attached to the modal. If you after click another thing to delete, it will delete both. – Pedro Lourenço Apr 11 '16 at 11:07
  • 1
    for the issue on the previous comments Pedro noted. $('#confirm').unbind() helps to unbind attached events – shivg May 10 '16 at 07:29
  • Check my answer here - http://stackoverflow.com/questions/8982295/confirm-delete-modal-dialog-with-twitter-bootstrap/37307703#37307703 for a reusable component. – Maleen Abewardana May 18 '16 at 18:42
  • @NigelAngel If I no of times click on `Cancel` button. Then the `.one('click', '#delete', function(e) {})` call no of times. If i click first 3 times cancel button then click on `Delete` button my `.one({})` executes 4 times. Please check. – Chinmay235 Aug 23 '17 at 12:53
  • //clear all existing events of modal dialog as shown below before opening it in order to prevent delete called multiple times $('#confirm').off(); – Ramireddy Ambati Oct 05 '17 at 05:24
18

You can use Bootbox dialog boxes

$(document).ready(function() {

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

Plunker Demo

Murali Murugesan
  • 22,423
  • 17
  • 73
  • 120
  • 3
    Be careful, bootbox may conflict with bootstrap modals. Sorry for responding to old question but I just came across with this problem. – SuperManSL Jan 05 '16 at 21:51
12

I've the same problem just today. This is my solution (which I think is better and simpler):

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

And in my .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);
}

Using unbind before the one prevents that the removal function is invoked at the next opening of the dialog.

I hope this could be helpful.

Follow a complete example:

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>
isherwood
  • 58,414
  • 16
  • 114
  • 157
Alessandro
  • 4,382
  • 8
  • 36
  • 70
6

simple way to use modals is with eModal!

Ex from github:

  1. Link to 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>

Tip: You can use change the default label name! { label: 'Yes' | 'True'| 'OK' }

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

FIDDLE

For your button:

<button class='btn btn-danger btn-xs launchConfirm' type="button" name="remove_levels"><span class="fa fa-times"></span> delete</button></td>
Nick
  • 1,530
  • 2
  • 15
  • 22
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

Create modal dialog in HTML with id="confirmation" and use function showConfirmation.

Also remember you should to unbind (modal.unbind()) cancel and success buttons after hide modal dialog. If you do not make this you will get double binding. For example: if you open dialog once and press 'Cancel' and then open dialog in second time and press 'Ok' you will get 2 executions of success callback.

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/

Alexey Muravyov
  • 1,106
  • 13
  • 17
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>

This code is not working as below changes needed:

  1. Need to define id="cancel" on cancel button

     <button type="button" data-dismiss="modal" id="cancel" class="btn">Cancel</button>
    
  2. cancel click event changes as below

     $('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');
       });
     });
    
Cédric
  • 2,239
  • 3
  • 10
  • 28