1

I need to migrate my sweetalert1 JS plugin to Sweetalert2 Plugin.

However I am at a complete loss on how to migrate the following code:

swal("A wild Pikachu appeared! What do you want to do?", {
  buttons: {
    cancel: "Run away!",
    catch: {
      text: "Throw Pokéball!",
      value: "catch",
    },
    defeat: true,
  },
})
.then((value) => {
  switch (value) {

    case "defeat":
      swal("Pikachu fainted! You gained 500 XP!");
      break;

    case "catch":
      swal("Gotcha!", "Pikachu was caught!", "success");
      break;

    default:
      swal("Got away safely!");
  }
});

sweetalert1: https://sweetalert.js.org/guides/#advanced-examples

sweetalert2: https://sweetalert2.github.io/

Any help in formatting the code to sweetalert2 please?

user2513846
  • 1,151
  • 2
  • 16
  • 39

1 Answers1

1

First of all, SweetAlert2 doesn't allow more than 2 buttons by default, but you can accomplish the same by using custom HTML buttons with jQuery bindings as described in this question. For your specific problem, the outcome should be more or less like this:

    $(document).on('click', '.SwalBtn1', function() {
        //Some code 1
        console.log('Button 1');
        swal.clickConfirm();
        swal("Got away safely!");
    });
    $(document).on('click', '.SwalBtn2', function() {
        //Some code 2 
        console.log('Button 2');
        swal.clickConfirm();
        swal("Gotcha!", "Pikachu was caught!", "success");
    });
    $(document).on('click', '.SwalBtn3', function() {
        // Some code 3
        console.log('Button 3');
        swal.clickConfirm();
        swal("Pikachu fainted! You gained 500 XP!");
    });

    swal({
        title: 'Oh oh!',
        html: "<p>A wild Pikachu appeared! What do you want to do?</p>" +
            '<button class="SwalBtn1 swal2-custom-button swal2-styled">' + 'Run Away!' + '</button>' +
            '<button class="SwalBtn2 swal2-custom-button swal2-styled">' + 'Throw Pokéball!' + '</button>' +
            '<button class="SwalBtn3 swal2-custom-button swal2-styled">' + 'Defeat!' + '</button>',
        showCancelButton: false,
        showConfirmButton: false
    });
.swal2-custom-button {
  background-color: #3085d6;
  color: #fff;
  border: 0;
  border-radius: .2em;
}
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@7.25.0/dist/sweetalert2.all.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

There is a documentation page on the SweetAlert2 repo that gives a better explanation (and cool examples!) on migrating the rest of the component. But this should get you in the path of what you need to do.

Limon Monte
  • 52,539
  • 45
  • 182
  • 213