Home > Mobile >  How to implement a reusable confirmation dialog with Bootstrap modals and jQuery?
How to implement a reusable confirmation dialog with Bootstrap modals and jQuery?

Time:11-15

I have 2 different functions that I would like to have a confirmation before execution. Normally I would just create 2 different confirmation dialog for each function, but I am wondering if there's a way to make use of a reusable modal dialog for both functions.

I've tried the following where I would pass in the function to be called to confirmDialog(). However, it would cause the function to 'stack' for subsequent confirmations since the event would bind every time confirmDialog() is called. I've tried unbind() of the buttons but that doesn't seem to work.

Modal:

<div class="modal fade" id="confirmDialog" tabindex="-1" role="dialog" data-backdrop="static" data-keyboard="false">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <div class="modal-title">Confirm Cancel?</div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" id="confirm-yes">Yes</button>
                <button type="button" class="btn btn-secondary" id="confirm-no">No</button>
            </div>
        </div>
    </div>
</div>

JavaScript:

$("#btn-cancel-alert").on("click", function () {
  var myid = $(this).val();
  var callbackfunc = myfunction(myid);
  menu.confirmDialog(callbackfunc);
});
var menu = {
  confirmDialog: function (callbackfunc) {
    $("#confirmDialog").modal("show");
    $("#confirmDialog")
      .on("click", "#confirm-yes", function () {
        callbackfunc;
        $("#confirmDialog").modal("hide");
        // Tried to unbind at the end >> ('#confirm-yes').unbind();
      })
      .on("click", "#confirm-no", function () {
        $("#confirmDialog").modal("hide");
        // Tried to unbind here.
      });
  }
}

;

CodePudding user response:

You're not adding listeners to the buttons, you're adding listeners to the dialog. So there are no listeners on the buttons to remove. Additionally, if the yes button gets clicked, the no listener will not be unbound (and vice-versa).

Looking at the jQuery docs, they say unbind() is deprecated - you should be using off() instead. And you should probably be using namespaced events just in case at some point you want to add other listeners.

var menu = {
  confirmDialog: function (callbackfunc) {
    const $yesButton = $("#confirm-yes");
    const $noButton = $("#confirm-no");
    $("#confirmDialog").modal("show");
    
    $yesButton.on("click.confirming", e => {
        callbackfunc();
        $yesButton.off("click.confirming");
        $noButton.off("click.confirming");
    };
    $noButton.on("click.confirming", e => {
        $yesButton.off("click.confirming");
        $noButton.off("click.confirming");
    }
  }
}
  • Related