SweetAlert2 - Bind another event to cancel button?
Asked Answered
B

8

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?

Brough answered 21/2, 2017 at 21:33 Comment(2)
limonte.github.io/sweetalert2/#dismiss-handleButtress
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?Brough
H
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
   }
});
Hughett answered 14/8, 2017 at 2:10 Comment(0)
P
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.

Pap answered 7/11, 2017 at 5:17 Comment(0)
T
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');
        }

    });
Toehold answered 7/8, 2018 at 7:7 Comment(0)
H
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
   }
});
Hughett answered 14/8, 2017 at 2:10 Comment(0)
T
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');
        }
    });
Thadthaddaus answered 17/8, 2020 at 8:35 Comment(0)
G
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**');
                    }
                });
Geopolitics answered 24/8, 2019 at 7:53 Comment(0)
C
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>`
});
Corves answered 2/9, 2020 at 0:40 Comment(0)
E
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');
                }
            });
Efflux answered 6/2, 2023 at 8:54 Comment(1)
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.Nonie
O
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');
        }
    })
}
Ornithopod answered 28/8, 2023 at 22:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.