Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return value from sweetAlert [duplicate]

I'm using sweetalert plugin to show notification... Now I need to get value from yes/no confirm

function confirm(message) {
 swal({
  title: "Are you sure?",
  text: message,
  type: "warning",
  showCancelButton: true,
  confirmButtonColor: "#DD6B55",
  confirmButtonText: "Yes",
  cancelButtonText: "No",
  closeOnConfirm: false,
  closeOnCancel: false
},
function(isConfirm){
  if (isConfirm) {
    return true;
  } else {
    return false;
  }
});
}

Then

if (confirm("my message")) myFunction();

I can call myFunction() from isConfirm of swal, but I have lot of "myFunction()" and I don't want to rewrite swal for each of these...

like image 273
FireFoxII Avatar asked Dec 05 '25 20:12

FireFoxII


1 Answers

You can do so with many different solutions:

Asynchronousity

function confirm(message) {
  return new Promise(resolve => swal({
    title: "Are you sure?",
    text: message,
    type: "warning",
    showCancelButton: true,
    confirmButtonColor: "#DD6B55",
    confirmButtonText: "Yes",
    cancelButtonText: "No",
    closeOnConfirm: false,
    closeOnCancel: false
  },
  function(isConfirm){
    if (isConfirm) {
      resolve(true);
    } else {
      resolve(false);
    }
  });
}
(async() => {
  if (await confirm("You can no longer restore your file afterwards")) myFunction()
})();

In this code, we use a Promise to send the data outside of the confirmation function inside swal.

Directly Substituting myFunction

function confirm(message, myFunction) {
  swal({
    title: "Are you sure?",
    text: message,
    type: "warning",
    showCancelButton: true,
    confirmButtonColor: "#DD6B55",
    confirmButtonText: "Yes",
    cancelButtonText: "No",
    closeOnConfirm: false,
    closeOnCancel: false
  },
  (z) => { myFunction(Boolean(z)) }
  });
}
confirm("You can no longer restore your file afterwards",(...args){
  myFunction([...args]);
});

Because the isConfirm is already returning something that can be differed by true and false, we can directly put myFunction inside the Swal, so you simply have to run the confirm and add a parameter function to run the myFunction in a separate method, yet still obtaining the working results.

I advise you to use the 2nd method because it keeps things synchronous, and will save you time converting code to asynchronous functions.

like image 78
Jake Avatar answered Dec 08 '25 09:12

Jake



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!