12

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?

Limon Monte
  • 52,539
  • 45
  • 182
  • 213
Piet
  • 2,188
  • 5
  • 19
  • 30
  • https://limonte.github.io/sweetalert2/#dismiss-handle – Limon Monte Feb 21 '17 at 21:44
  • That is not exactly what I mean because this is closing the alert. I need to handle the cancel event without closing the alert. Is this possible? – Piet Feb 22 '17 at 07:36

8 Answers8

21

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.

PJunior
  • 2,649
  • 1
  • 33
  • 29
13

with a little customization to @Raditya Adi Baskara answer,

swal({
        title: "$titleWarnignBox",
        type: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#36c6d3',
        cancelButtonColor: '#d33',
        confirmButtonText: '$confrimBtn',
        cancelButtonText: '$cancelBtn'
    }).then(function(result){
        if(result.value){
            console.log('good');
        }else if(result.dismiss == 'cancel'){
           console.log('cancel');
        }

    });
Hakeem Nofal
  • 149
  • 2
  • 4
8
  1. You could create a custom html file and have a cancel button in that which will fire off you own cancel handler.

for example

<html> <!--custom.html-->      
  <button id="confirmBtn">confirm<button>
  <button id="cancelBtn">cancel<button>
<html>

$.get("custom.html", function (data) {
        swal({
            html: data,
            showCloseButton: false,
            showCancelButton: false,
            showConfirmButton: false
        });
        $("#cancelBtn").click(function () {
            //handle your cancel button being clicked
            $.when($.ajax({....})).then(function() {
                 // when all AJAX requests are complete
             });
        });
        $("#confirmBtn").click(function () {
            //handle your confirm button being clicked
        });
    });
  1. You could just recall the popup on cancel. Add this to your swal function.

    function (dismiss) {
       if (dismiss === 'cancel') {
          swal({..});            
       }
    }
    

So in full

swal({
   title: 'Swal Title',
   text: 'Your swal text',
   type: 'warning',
   showCancelButton: true,
   cancelButtonText: 'cancel'
}).then(function(){
   //Confirmed
}, function(dismiss){
   if(dismiss == 'cancel'){
      //swal({..}); //un-comment this line to add another sweet alert popup on cancel
   }
});
Hayden Passmore
  • 1,135
  • 2
  • 12
  • 34
4

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');
        }
    });
2

In sweetalert 2

            swal.fire({
                title: "Notice",
                text: "Are you sure ?",
                showCancelButton: true,
                type: 'error',
                cancelButtonColor: '#d33',
            })
                .then((res) => {
                    if(res.value){
                        console.log('confirmed');
                    }else if(res.dismiss == 'cancel'){
                        console.log('cancel');
                    }
                    else if(res.dismiss == 'esc'){
                        console.log('cancle-esc**strong text**');
                    }
                });
1

In sweetalert2, if you want to prevent the close when the cancel button is clicked, you can add your own custom buttons as html: (Run it live)

var onBtnClicked = (btnId) => {
  // Swal.close();
  alert("you choosed: " + btnId);
};
Swal.fire({
  title: "What you want to do?",
  icon: "warning",
  showConfirmButton: false,
  showCloseButton: true,
  html: `
     <p>select an action</p>
    <div>
      <button class="btn btn-primary" onclick="onBtnClicked('reply')">Reply</button>
      <button class="btn btn-danger" onclick="onBtnClicked('delete')">Delete</button>
    </div>`
});
yaya
  • 7,675
  • 1
  • 39
  • 38
0

sweetalert 2 handle cancel or confirm (with input form)

                Swal.fire({
                title: "Please enter TPL coverage",
                input: 'text',
                showCancelButton: true,
                allowOutsideClick: false,
                preConfirm: (value) => {
                    if (value > 100000000) {
                        Swal.showValidationMessage('Max Rp.100.000.000 !')
                    };
                }
            }).then((result) => {
                if (result.isConfirmed) {
                    if (result.value) {
                        let typeOfCarid = $('#typeOfCarid').val();
                        let calculate;
                        if (typeOfCarid != 2) {
                            if (result.value > 50000000) {
                                calculate = (25000000 * 1 / 100) + (25000000 * 0.5 / 100) + ((result.value - 50000000) * 0.25 / 100);
                                //Correct By Calculate Manual MF
                            } else if (result.value > 25000000) {
                                calculate = (25000000 * 1 / 100) + ((result.value - 25000000) * 0.5 / 100);
                                //Correct By Calculate Manual MF
                            } else {
                                calculate = (result.value * 1 / 100);
                            }
                            $('#tplRate').val(calculate);
                        } else {
                            alert('Ini Bus / Truck');
                        }
                    }
                } else if (result.isDismissed) {
                    alert('dismis');
                }
            });
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Feb 20 '23 at 00:37
0

this is the best way i get it going

    function sw_alert() {
    Swal.fire({
        title: 'Your title',
        icon: 'warning',
        showDenyButton: true,
        showCancelButton: true,         
        confirmButtonColor: '#000000',
        cancelButtonColor: '#a8a8a8',
        confirmButtonText: 'Yes',
        denyButtonText: 'No',
    }).then((result) => {
        /* Read more about isConfirmed, isDenied below */
        if (result.isConfirmed) {
             console.log('Yes');
        } else if (result.isDenied) {
             console.log('No');
        } else {
             console.log('cancel');
        }
    })
}
jeyglo
  • 137
  • 1
  • 5