How To Use Sweet alert

Mohammad picture Mohammad · Jan 8, 2015 · Viewed 58.6k times · Source

This Is My HTML Code I Have Two Input Button That I Want To Show Sweet Alert When a user Clicks on any Button

<tr class="examples odd" id="UserId_1" role="row">
   <td class="sorting_1">1</td>
   <td>admin</td><td>Mohammad</td>
   <td>Farzin</td><td class="warning"><input type="button"
   value="Delete" class="sweet-5" id="btn_Delete1"></td>
</tr>
<tr class="examples even" id="UserId_5" role="row">
   <td class="sorting_1">2</td>
   <td>11</td><td>11</td>
   <td>11</td><td class="warning"><input type="button" value="Delete" class="sweet-5"
   id="btn_Delete5"></td>
</tr>   

Script

$(document).ready(function () {
document.querySelector('td.warning input').onclick = function () {
    swal({
        title: "Are you sure?",
        text: "You will not be able to recover this imaginary file!",
        type: "warning",
        showCancelButton: true,
        confirmButtonClass: 'btn-danger',
        confirmButtonText: 'Yes, delete it!',
        cancelButtonText: "No, cancel plx!",
        closeOnConfirm: false,
        closeOnCancel: false
        },
     function (isConfirm) {
        if (isConfirm) {
            swal("Deleted!", "Your imaginary file has been deleted!", "success");
            } else {
                swal("Cancelled", "Your imaginary file is safe :)", "error");
            }
        });
    };

});

Only The First Input Button Shows Sweet Alert, but when I click the second button nothing happens

Answer

Ervin picture Ervin · Feb 17, 2017

You were probably using SweetAlert version 2 and your code applies to version 1. This should work:

swal({
  title: 'Are you sure?',
  text: 'Some text.',
  type: 'warning',
  showCancelButton: true,
  confirmButtonColor: '#DD6B55',
  confirmButtonText: 'Yes!',
  cancelButtonText: 'No.'
}).then(() => {
  if (result.value) {
    // handle Confirm button click
  } else {
    // result.dismiss can be 'cancel', 'overlay', 'esc' or 'timer'
  }
});
<script src="https://unpkg.com/[email protected]/dist/sweetalert2.all.js"></script>

Source: Migration from Swal1 to Swal2