ashokkumarn12
ashokkumarn12

Reputation: 145

How to show SweetAlert in JavaScript

How can I show SweetAlert in this JavaScript code?

function removeReg(del_reg) {
  if (confirm("Are you sure you want to delete? \n the reg name : " + del_reg)) {
    // Code goes here
  }
}

I just want to call SweetAlert in the if condition, i.e. in SweetAlert, I need to show the message "Are you sure you want to delete?".

Upvotes: 3

Views: 7000

Answers (1)

Rick
Rick

Reputation: 4124

Call swal() with your custom options in the removeReg(del_reg) function and use the Promise returned by swal() to determine what is the user's choice:

  • If the user clicked YES, the returned value will be true
  • If the user clicked NO or pressed the Esc key, the returned value will be null

var button = document.getElementById('remBtn')

function removeReg(del_reg) {
  swal({
      text: "Are you sure you want to delete? \n the reg name : " + del_reg,
      icon: "error",
      buttons: ['NO', 'YES'],
      dangerMode: true
    })
    .then(function(value) {
      console.log('returned value:', value);
    });
}

button.addEventListener('click', function() {
  console.log('clicked on button')
  removeReg('SomeCustomRegName');
});
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
<button id="remBtn">Remove Registered Name</button>

More on the advanced examples of SweetAlert

Upvotes: 7

Related Questions