How do I know which button is click when bootstrap modal closes

Here is my modal html code:

<div class="modal fade" id="delete-file-modal" role="dialog">
  <div class="modal-dialog">
      <div class="modal-content">
          <form class="form-horizontal" method="post" id="delete_file_form">
              <div class="modal-body">
                  Are you sure you want to delete this file?
              </div>
              <div class="modal-footer">
                  <button data-dismiss="modal" class="btn btn-danger" name="in_confirm_insert" id="confirm-delete-button">Delete</button>
                  <button data-dismiss="modal" class="btn btn-default" name="in_confirm_insert" id="cancel-delete-button">Cancel</button>
              </div>
          </form>
      </div>
  </div>
</div>

and here is my javascript code:

$('#delete-file-modal').on('hidden.bs.modal', function (e) {
  var delete_button = $(e.target).is("#confirm-delete-button");
  if(delete_button === true){
    alert("file deleted.");
  } else {
    alert("delete failed.");
  };
});

I need to be able to check if the delete button is clicked when the delete-file-modal is closed. Is there something else missing in my javascript code?


solution

Within the hidden.bs.modal event listener, e.target refers to the modal element, not the clicked element.

If you want to determine which button triggered the modal to close, you would have to add event listeners to the button elements inside the modal. Within the button event listeners, you could listen to the hidden.bs.modal event to determine if the modal was closed.

Example Here

$('#delete-file-modal .modal-footer button').on('click', function (e) {
  var $target = $(e.target); // Clicked button element
  $(this).closest('.modal').on('hidden.bs.modal', function () {
      console.log($target); // Logged if the clicked button actually closed the modal
  });
});

As a side note, according to Bootstrap documentation, the show.bs.modal/shown.bs.modal events have the relatedTarget property attached to the event.

If caused by a click, the clicked element is available as the relatedTarget property of the event.

Thus, you can determine the element that triggered the modal to open with e.relatedTarget:

Example Here

$('#delete-file-modal').on('show.bs.modal', function (e) {
  console.log(e.relatedTarget); // Logs the clicked element that opened the modal
});

It would be nice if they had a property like that associated with the hide.bs.modal/hidden.bs.modal events. As of writing this, there currently isn’t.