kikinet kikinet - 3 months ago 18
jQuery Question

sweetAlert preventDefault and return true

I tried sweeAlert plugin, which works perfectly, but I cant figure out how to do default stuff after confirm.

$(document).ready(function () {
function handleDelete(e){
e.preventDefault();
swal({
title: "Are you sure?",
text: "You will not be able to recover the delaer again!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete!",
closeOnConfirm: false
},
function (isConfirm) {
if (isConfirm) {
return true;
}
});
};
});


and the button

<a href="{plink delete! $row->id_dealers}" class="delete" onclick"handleDelete(event);">&nbsp;</a>
//{plink delete! $row->id_dealers} Nette -> calls php delete handler


I also tried
unbind()
and
off()
instead of
return false
, doesnt work.
Earlier I used
confirm()
with
return true
and
return false
in
onclick
attribute, it works, but it looks awful.

Answer

You can try something like this

$(document).ready(function () {
  $('.delete').on('click',function(e, data){
    if(!data){
      handleDelete(e, 1);
    }else{
      window.location = $(this).attr('href');
    }
  });
});
function handleDelete(e, stop){
  if(stop){
    e.preventDefault();
    swal({
      title: "Are you sure?",
      text: "You will not be able to recover the delaer again!",
      type: "warning",
      showCancelButton: true,
      confirmButtonColor: "#DD6B55",
      confirmButtonText: "Yes, delete!",
      closeOnConfirm: false
    },
    function (isConfirm) {
      if (isConfirm) {
        $('.delete').trigger('click', {});
      }
    });
  }
};

Here is a demo http://jsbin.com/likoza/1/edit?html,js,output

Another way is the use a form instead of a href.

The markup would look like this

<form action="">
  <input type="submit" ...... />
</form>

and instead of window.location = $(this).attr('href'); you can just say form.submit()


Update

If there are multiple elements on the page then trigger can be used like this

$(e.target).trigger('click', {});

Here is a demo http://output.jsbin.com/likoza/2

Comments