Frank Provost Frank Provost - 5 months ago 21
Javascript Question

jQuery custom confirm boxes allowing / blocking cought events

I have something like a delete form which should require pressing "Yes- Delete" within modal confirmation box. So basically someting like this

$('#my-form').on('submit', function(e) {
var r = confirm("Really Delete?");

if (r != true) {
e.preventDefault();
}
});


So this is working, but I do not want the ugly browser confirm boxes. I'd like to use my own dialogs.

My Problem is basically that the confirm method stops the script execution, therefore I do not need to call preventDefault if nothing is pressed yet.

Are there any good solutions / best practices for this?

Answer

You can use jquery confirm and if user confirm you can call ajax:

$('.ajax-form').on('submit', function(e) {
  var self = $(this);
  $(".confirm").confirm({
    text: self.data('confirmation'),
    title: "Confirmation required",
    confirm: function(button) {
        $.ajax({
            method: self.attr('method') || 'GET',
            url: self.attr('action'), 
            data: self.serialize(),
            success: function() {
               // deleted
            }
        });
    }
  });
  e.preventDefault();
});

and you can have html like this:

<form action="/delete" method="POST" data-confirmation="Really Delete?">

</form>