Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SweetAlert2 - Bind another event to cancel button?

I am using the latest version of the awesome SweetAlert2 jquery plugin.

I have a simple SweetAlert with 2 buttons. 1 button is the confirm button, the other is the cancel button. I am using the html option to add a text input to the alert. When the user press the confirm button an AJAX call is executed and the alert is closed.

Now I want to use the cancel button to execute some other code instead of the default action which is closing the alert. (The user can close the alert using the showCloseButton: true).

So in short: How to remove the closing handler and add a own custom handler to the cancel button of swal?

like image 836
Piet Avatar asked Feb 21 '17 21:02

Piet


People also ask

How do I get the cancel button on sweet alert?

Just add showCloseButton: true and this will show the close X icon in the top right corner of the pop up. Note it is not available in SweetAlert1 library which is now deprecated, I would suggest using SweetAlert2.

How do I use Swal alert?

Once the library is set up, creating a SweetAlert message is very easy. All you have to do is call the swal() function. swal("Here's a message!", " Have a nice day!")


2 Answers

Just add your custom function to catch the rejection, for example:

swal({
   title: 'Some title',
   text: 'some text for the popup',
   type: 'warning',
   showCancelButton: true,
   cancelButtonText: 'Some text for cancel button'
}).then(function(){
   // function when confirm button clicked
}, function(dismiss){
   if(dismiss == 'cancel'){
       // function when cancel button is clicked
   }
});

You can even add more function to catch another dismiss event, just read SweetAlert2 Docs for more info about dismiss event.

like image 160
Raditya Adi Baskara Avatar answered Nov 16 '22 02:11

Raditya Adi Baskara


In SweetAlert2.

Swal.fire({
        title: 'Title here',
        showCloseButton: false,
        showCancelButton: true,
        showConfirmButton: false,
        focusConfirm: false,
        allowOutsideClick: false,
        allowEscapeKey: false,
        cancelButtonText: 'Cancel Payment'
    }).then(function(res) {
        if (res.isDismissed) {
            alert('Cancel button clicked');
        }
    });
like image 26
Sandeep Kumar Avatar answered Nov 16 '22 01:11

Sandeep Kumar