17

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.

N'Bayramberdiyev
  • 4,947
  • 7
  • 18
  • 39
Sukhwinder Sodhi
  • 397
  • 1
  • 3
  • 15

8 Answers8

20

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>
G07cha
  • 3,546
  • 1
  • 20
  • 38
  • any idea how to add spaces between buttons – Miloud BAKTETE Sep 26 '17 at 08:18
  • @baktetemiloud, you can add classes to the buttons and style them as you want using CSS. – G07cha Sep 26 '17 at 16:34
  • @KonstantinAzizov I am using older version of sweetalert, how can i add custom buttons in it !? – bharat parmar Jan 17 '18 at 12:13
  • @bharatparmar, actually `html` should be available in the older version of sweetalert, what problem are you facing with current implementation? – G07cha Jan 17 '18 at 13:50
  • Unfortunately, this stopped working in sweetalert2 4.2.6. – Richard Cook Jun 27 '18 at 23:49
  • 1
    Specifically this change: https://github.com/sweetalert2/sweetalert2/compare/v4.2.5...v4.2.6#diff-ec611670c4fa1523baf034d3d3cb96ccL485. Now nodes are cloned as they are added to the inner HTML (which probably strips event handlers). – Richard Cook Jun 27 '18 at 23:59
14

The above answer didn't work for me, so I did the following:

    $(document).on('click', '.SwalBtn1', function() {
        //Some code 1
        console.log('Button 1');
        swal.clickConfirm();
    });
    $(document).on('click', '.SwalBtn2', function() {
        //Some code 2 
        console.log('Button 2');
        swal.clickConfirm();
    });

$('#ShowBtn').click(function(){
    swal({
        title: 'Title',
        html: "Some Text" +
            "<br>" +
            '<button type="button" role="button" tabindex="0" class="SwalBtn1 customSwalBtn">' + 'Button1' + '</button>' +
            '<button type="button" role="button" tabindex="0" class="SwalBtn2 customSwalBtn">' + 'Button2' + '</button>',
        showCancelButton: false,
        showConfirmButton: false
    });
 });
.customSwalBtn{
  background-color: rgba(214,130,47,1.00);
    border-left-color: rgba(214,130,47,1.00);
    border-right-color: rgba(214,130,47,1.00);
    border: 0;
    border-radius: 3px;
    box-shadow: none;
    color: #fff;
    cursor: pointer;
    font-size: 17px;
    font-weight: 500;
    margin: 30px 5px 0px 5px;
    padding: 10px 32px;
 }
<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="ShowBtn" class="customSwalBtn">Alert</button>
Ricardo Melo
  • 329
  • 1
  • 3
  • 13
3

I once needed to add the third button to SweetAlert2 popup. The simplest way in my case was to use footer which can be either plain text or HTML:

$(function() {
    $('.btn').click(function(e) {
        e.preventDefault();
        
        Swal.fire({
            icon: 'warning',
            title: 'Are you sure?',
            text: 'You won\'t be able to revert this!',
            showCloseButton: true,
            showCancelButton: true,
            footer: '<a href="#!" id="some-action">Some action</a>'
        }).then((result) => {
            console.log(result);
        });
    });
    
    $(document).on('click', '#some-action', function(e) {
        e.preventDefault();
        console.log('Some action triggered.');
    });
});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@9"></script>

<div class="text-center">
    <button type="button" class="btn btn-primary my-3">Click me</button>
</div>
N'Bayramberdiyev
  • 4,947
  • 7
  • 18
  • 39
3

For sweetalert2, this worked for me: (Run it live)

var onBtnClicked = (btnId) => {
  Swal.close();
  if (btnId != "cancel") Swal.fire("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>
      <button class="btn btn-secondary" onclick="onBtnClicked('cancel')">Cancel</button>
    </div>`
});
yaya
  • 4,522
  • 1
  • 19
  • 24
2

Richard Cook remarked above that the original answer (provided by Konstantin Azizov) stopped working with version 4.2.6 of SweetAlert2. He suggested this had to do with nodes being cloned as they are added to the html. I don't know SweetAlert2 well enough to say whether he was right or not. I could see, though, that my buttons got added but the onclick callback functions never got called.

With a little effort, I was able to get this to work with the current release of SweetAlert2. To make it work I had to assign the onclick events to the buttons at a later point. I ended up adding ids to the buttons, making them easy to select from jQuery. Then I added on onOpen function to my swal object and in there, connected the logic to associate the callback functions. Below is a snippet of the code that works for me.

Also note that the message and buttons use some existing SweetAlert2 classes so they do have the same look as the existing UI elements. A word of caution, I did try using the swal2-confirm and swal2-cancel classes. When I did that I ran into some issues. It may be that SweetAlert2 code is dependent on there only being a single element that uses that class. I didn't have time to chase it down so I just stopped using those classes.

function createButton(text, id) {
        return $('<button class="swal2-input swal2-styled" id="'+id+'">'+text+'</button>');
    }

    function createMessage(text) {
        return $('<div class="swal2-content" style="display: block;">'+text+'</div>');
    }

function swThreeButton(msg, textOne, textTwo, textThree, callbackOne, callbackTwo, callbackThree) {

        var buttonsPlus = $('<div>')
                .append(createMessage(msg))
                .append(createButton(textOne,'sw_butt1'))
                .append(createButton(textTwo,'sw_butt2'))
                .append(createButton(textThree,'sw_butt3'));

        swal({
            title: 'Select Option',
            html: buttonsPlus,
            type: 'question',

            showCancelButton: false,
            showConfirmButton: false,
            animation: false,
            customClass: "animated zoomIn",
            onOpen: function (dObj) {
                $('#sw_butt1').on('click',function () {
                   swal.close();
                   callbackOne();
                });
                $('#sw_butt2').on('click',function () {
                    swal.close();
                    callbackTwo();
                });
                $('#sw_butt3').on('click',function () {
                    swal.close();
                    callbackThree();
                });
            }
        });

    };


KW402
  • 21
  • 1
2

We recently released SweetAlert2 v10 with the support for third "deny" button:

enter image description here

Swal.fire({
  title: 'Do you want to save the changes?',
  showDenyButton: true,
  showCancelButton: true,
  confirmButtonText: `Save`,
  denyButtonText: `Don't save`,
}).then((result) => {
  /* Read more about isConfirmed, isDenied below */
  if (result.isConfirmed) {
    Swal.fire('Saved!', '', 'success')
  } else if (result.isDenied) {
    Swal.fire('Changes are not saved', '', 'info')
  }
})
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@10"></script> 

Read the release notes for v10: https://github.com/sweetalert2/sweetalert2/releases/v10.0.0

Limon Monte
  • 44,025
  • 43
  • 163
  • 189
0

For sweetalert2 this worked 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>
0

This is now very easy with ES6.

Please see here: how to add Unlimited buttons

  createSwalButton = async () => {

    let swalButton = await swal({
      title: "Add Buttons?",
      text: "This will create a new button.",
      icon: "info",
      buttons: {
        buttonOne: {
          text: "First",
          value: "firstVal",
          visible: true,
          className: "swal-btn-cancel",
          closeModal: true,
        },
        buttonTwo: {
          text: "Second",
          value: "secondVal",
          visible: true,
          className: "swal-btn-confirm",
          closeModal: true
        },
        buttonThree: {
          text: "Third",
          value: "thirdVal",
          visible: true,
          className: "swal-btn-confirm",
          closeModal: true
        },
        buttonFour: {
          text: "Fourth",
          value: "fourthVal",
          visible: true,
          className: "swal-btn-confirm",
          closeModal: true
        },
        buttonFive: {
          text: "Fifth",
          value: "fifthVal",
          visible: true,
          className: "swal-btn-confirm",
          closeModal: true
        }
      },
    })

    if (swalButton === "firstVal") {    
      //do stuff
    }
  }

Ok, I might have gone overboard, but you see how it works.

Shout out to SWAL team! It is a great great product.

Israel Peck
  • 547
  • 2
  • 16