More than 2 buttons on sweetalert 2
Asked Answered
C

8

23

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.

Capability answered 1/9, 2016 at 9:54 Comment(0)
C
13

πŸŽ‰πŸŽ‰πŸŽ‰ 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) => {
  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@11"></script> 
Camaraderie answered 16/9, 2020 at 18:6 Comment(1)
Hello, I have tried that, but I am using a SweetAlert version that the dialog is launched using just swal, not swal.fire. I have updated the JS and CSS files, then replaced all occurrences of swal( by swal.fire( and dialog is shown, but very ugly. For example, text are aligned differently and icons are not shown. So I have realized that this version is not backward compatible. The only solution to have one more button is by using a custom HTML? – Shewmaker
H
25

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>
Hopi answered 1/9, 2016 at 10:34 Comment(6)
any idea how to add spaces between buttons – Mindoro
@baktetemiloud, you can add classes to the buttons and style them as you want using CSS. – Hopi
@KonstantinAzizov I am using older version of sweetalert, how can i add custom buttons in it !? – Salmonella
@bharatparmar, actually html should be available in the older version of sweetalert, what problem are you facing with current implementation? – Hopi
Unfortunately, this stopped working in sweetalert2 4.2.6. – Paredes
Specifically this change: github.com/sweetalert2/sweetalert2/compare/…. Now nodes are cloned as they are added to the inner HTML (which probably strips event handlers). – Paredes
A
17

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>
Ampereturn answered 24/3, 2017 at 23:49 Comment(0)
C
13

πŸŽ‰πŸŽ‰πŸŽ‰ 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) => {
  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@11"></script> 
Camaraderie answered 16/9, 2020 at 18:6 Comment(1)
Hello, I have tried that, but I am using a SweetAlert version that the dialog is launched using just swal, not swal.fire. I have updated the JS and CSS files, then replaced all occurrences of swal( by swal.fire( and dialog is shown, but very ugly. For example, text are aligned differently and icons are not shown. So I have realized that this version is not backward compatible. The only solution to have one more button is by using a custom HTML? – Shewmaker
B
4

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();
                });
            }
        });

    };


Brambly answered 21/6, 2019 at 19:42 Comment(1)
Didn't work at all for me - I get an alert with one "OK" button - none of my buttons show up. – Innocent
B
4

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>`
});
Bornstein answered 2/9, 2020 at 0:34 Comment(0)
P
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/[email protected]/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>
Polish answered 12/12, 2019 at 14:27 Comment(0)
I
0

Sweet Alert has the solution right on their guide page: https://sweetalert.js.org/guides/#customizing-buttons

After trying all the above solutions (none of which worked), this worked perfectly fine :-)

Innocent answered 2/5, 2023 at 20:53 Comment(0)
H
-1

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>
Harmony answered 12/9, 2020 at 21:32 Comment(0)

© 2022 - 2024 β€” McMap. All rights reserved.