More than 2 buttons on sweetalert 2

Sukhwinder Sodhi picture Sukhwinder Sodhi · Sep 1, 2016 · Viewed 49.2k times · Source

I have a sweetalert with 2 buttons but I want to have one more button in it. For example, as of now, I have yes and no I want to add one more button say later. Please help.

$("#close_account").on("click", function(e) {
    e.preventDefault();
    swal({
        title: "Are you sure?",
        text: "You will not be able to open  your account!",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "Yes, close my account!",
        closeOnConfirm: false
    },
    function() {
        window.location.href="<?php echo base_url().'users/close_account' ?>"
    });
});

Thanks in advance.

Answer

G07cha picture G07cha · Sep 1, 2016

You should use custom HTML with jQuery event bindings, it works almost the same, only problem that you need to add styling for buttons by yourself because SweetAlert classes don't work for me.

$(document).ready(function() {
  $("#close_account").on("click", function(e) {
    var buttons = $('<div>')
    .append(createButton('Ok', function() {
       swal.close();
       console.log('ok'); 
    })).append(createButton('Later', function() {
       swal.close();
       console.log('Later'); 
    })).append(createButton('Cancel', function() {
       swal.close();
       console.log('Cancel');
    }));
    
    e.preventDefault();
    swal({
      title: "Are you sure?",
      html: buttons,
      type: "warning",
      showConfirmButton: false,
      showCancelButton: false
    });
  });
});

function createButton(text, cb) {
  return $('<button>' + text + '</button>').on('click', cb);
}
<link href="https://cdn.jsdelivr.net/sweetalert2/4.2.4/sweetalert2.min.css" rel="stylesheet"/>
<script src="https://cdn.jsdelivr.net/sweetalert2/4.2.4/sweetalert2.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id="close_account">Show</button>