sweet alert continue submitting form on confirm

user796443 picture user796443 · Aug 23, 2015 · Viewed 64.3k times · Source

I've this sweetalert triggered on submit of a form.

$(".swa-confirm").on("submit", function(e) {
        e.preventDefault();
        swal({
            title: $(this).data("swa-title"),
            text: $(this).data("swa-text"),
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#cc3f44",
            confirmButtonText: $(this).data("swa-btn-txt"),
            closeOnConfirm: false,
            html: false
        }, function() {

        }
        );
    });

but on clicking confirm I want it to continue submiting the form...

Bad ideas come to mind, like:

var confirmed = false;
$(".swa-confirm").on("submit", function(e) {
    var $this = $(this);
    if (!confirmed) {
        e.preventDefault();
        swal({
            title: $(this).data("swa-title"),
            text: $(this).data("swa-text"),
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#cc3f44",
            confirmButtonText: $(this).data("swa-btn-txt"),
            closeOnConfirm: true,
            html: false
        }, function() {
            confirmed = true;
            $this.submit();
        });
    }
});

or moving swa to button click instead of on submit, and using on submit of a form.

but I don't like this solution, it looks frankesteini to me. Surely there is a better way

Answer

Omar Makled picture Omar Makled · Oct 27, 2015
$('#btn-submit').on('click',function(e){
    e.preventDefault();
    var form = $(this).parents('form');
    swal({
        title: "Are you sure?",
        text: "You will not be able to recover this imaginary file!",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "Yes, delete it!",
        closeOnConfirm: false
    }, function(isConfirm){
        if (isConfirm) form.submit();
    });
});