44

In this code form is submitted even i am clicking on no

document.querySelector('#from1').onsubmit = function(){

 swal({
    title: "Are you sure?",
    text: "You will not be able to recover this imaginary file!",
    type: "warning",
    showCancelButton: true,
    confirmButtonColor: '#DD6B55',
    confirmButtonText: 'Yes, I am sure!',
    cancelButtonText: "No, cancel it!",
    closeOnConfirm: false,
    closeOnCancel: false
 },
 function(isConfirm){

   if (isConfirm){
     swal("Shortlisted!", "Candidates are successfully shortlisted!", "success");

    } else {
      swal("Cancelled", "Your imaginary file is safe :)", "error");
    }
 });
};
Nishit Maheta
  • 6,021
  • 3
  • 17
  • 32

13 Answers13

58

You will need to prevent default form behaviour on submit. After that you will need to submit form programmatically in case of Ok button is selected.

Here is how it could look like:

document.querySelector('#from1').addEventListener('submit', function(e) {
  var form = this;

  e.preventDefault(); // <--- prevent form from submitting

  swal({
      title: "Are you sure?",
      text: "You will not be able to recover this imaginary file!",
      icon: "warning",
      buttons: [
        'No, cancel it!',
        'Yes, I am sure!'
      ],
      dangerMode: true,
    }).then(function(isConfirm) {
      if (isConfirm) {
        swal({
          title: 'Shortlisted!',
          text: 'Candidates are successfully shortlisted!',
          icon: 'success'
        }).then(function() {
          form.submit(); // <--- submit form programmatically
        });
      } else {
        swal("Cancelled", "Your imaginary file is safe :)", "error");
      }
    })
});

UPD. Example above uses sweetalert v2.x promise API.

Demo: http://plnkr.co/edit/YTY7PDs5Uh1XGUo9ic1s?p=preview

dfsq
  • 191,768
  • 25
  • 236
  • 258
  • Now nothing is happening after I am clicking Ok button. It stuck with the sweet alert –  Jun 30 '15 at 12:16
  • Uncaught TypeError: object is not a function is showing –  Jun 30 '15 at 12:18
  • Check the working demo. Then compare to your code, you probably confused something. – dfsq Jun 30 '15 at 12:21
  • Checked your code but it is not working in my code, Again same error is showing –  Jun 30 '15 at 12:32
  • if i am removing suceess swal that accure after confirmation then it is giving me error –  Feb 28 '18 at 14:15
  • The code you are using is from prior the latest version 2. Please read up on Upgrading from 1.X. You should use promise to keep track of user interaction. – Martin Chinome Mar 21 '18 at 19:42
  • @MARTINALBARRACIN Cool, thanks for letting me know. Updated example. – dfsq Mar 22 '18 at 10:01
  • while using solution when i am trying to redirect to home page. `this.router.navigate(['']);` i am getting below error. `core.js:6142 ERROR Error: Uncaught (in promise): TypeError: Cannot read properties of undefined (reading 'router')` – Jignesh Panchal May 25 '22 at 06:40
  • @JigneshPanchal you are loosing context. Use arrow function to have correct reference `this`. – dfsq May 25 '22 at 08:27
9
document.querySelector('#from1').onsubmit = function(e){

 swal({
    title: "Are you sure?",
    text: "You will not be able to recover this imaginary file!",
    type: "warning",
    showCancelButton: true,
    confirmButtonColor: '#DD6B55',
    confirmButtonText: 'Yes, I am sure!',
    cancelButtonText: "No, cancel it!",
    closeOnConfirm: false,
    closeOnCancel: false
 },
 function(isConfirm){

   if (isConfirm){
     swal("Shortlisted!", "Candidates are successfully shortlisted!", "success");

    } else {
      swal("Cancelled", "Your imaginary file is safe :)", "error");
         e.preventDefault();
    }
 });
};
Bit_Pulse
  • 336
  • 1
  • 2
  • 16
  • 1
    In this form is submitting even I have not clicked on any of the button. This is a flash of the alert but then the form is submitted –  Jun 30 '15 at 12:13
  • 1
    This is not correct, e.preventDefault has to be outside the anonymous function. – Ibu Jul 15 '16 at 04:47
  • Code is ran regardless of what the function is doing – ricks Jul 18 '18 at 22:40
9

I have been having this issue with SweetAlert2 as well. SA2 differs from 1 and puts everything inside the result object. The following above can be accomplished with the following code.

Swal.fire({
    title: 'A cool title',
    icon: 'info',
    confirmButtonText: 'Log in'
  }).then((result) => {
    if (result['isConfirmed']){
      // Put your function here
    }
  })

Everything placed inside the then result will run. Result holds a couple of parameters which can be used to do the trick. Pretty simple technique. Not sure if it works the same on SweetAlert1 but I really wouldn't know why you would choose that one above the newer version.

8

You need To use then() function, like this

swal({
    title: "Are you sure?",
    text: "You will not be able to recover this imaginary file!",
    type: "warning",
    showCancelButton: true,
    confirmButtonColor: '#DD6B55',
    confirmButtonText: 'Yes, I am sure!',
    cancelButtonText: "No, cancel it!"
 }).then(
       function () { /*Your Code Here*/ },
       function () { return false; });
saka
  • 127
  • 1
  • 7
  • 2
    I get TypeError: Cannot read properties of undefined (reading 'then') .. and no I will not be using sweetalert 2 – Jaxx0rr Feb 26 '22 at 04:17
4

document.querySelector('#from1').onsubmit = function(e){

 swal({
    title: "Are you sure?",
    text: "You will not be able to recover this imaginary file!",
    type: "warning",
    showCancelButton: true,
    confirmButtonColor: '#DD6B55',
    confirmButtonText: 'Yes, I am sure!',
    cancelButtonText: "No, cancel it!",
    closeOnConfirm: false,
    closeOnCancel: false
 },
 function(isConfirm){

   if (isConfirm.value){
     swal("Shortlisted!", "Candidates are successfully shortlisted!", "success");

    } else {
      swal("Cancelled", "Your imaginary file is safe :)", "error");
         e.preventDefault();
    }
 });
};
Moode Osman
  • 1,715
  • 18
  • 17
  • 1
    no need `isConfirm.value`, you can use `if (isConfirm) { ... }` will return true if confirmed – Roy Ryando Jul 21 '19 at 13:27
  • The naming here is confusing. The input should be result instead of isConfirm. This result object contains properties like `isConfirmed`, `value`, and `isDenied` (https://sweetalert2.github.io/#three-buttons) – Ben Jones Jun 18 '22 at 15:29
  • 1
    I had to change `if (isConfirm.value)` to `if (isConfirm)` in order to correctly evaluate the boolean returned by the user's action - otherwise this is the only example here working for me. – cloudxix Sep 05 '22 at 03:49
3
swal({
    title: 'Are you sure?',
    text: "You won't be able to revert this!",
    type: 'warning',
    showCancelButton: true,
    confirmButtonColor: '#3085d6',
    cancelButtonColor: '#d33',
    confirmButtonText: 'Confirm!'
}).then(function(){
    alert("The confirm button was clicked");
}).catch(function(reason){
    alert("The alert was dismissed by the user: "+reason);
});
Hiran Walawage
  • 2,048
  • 1
  • 22
  • 20
3

100% working

Do some little trick using attribute. In your form add an attribute like data-flag in your form, assign "0" as false.

<form id="from1" data-flag="0">
    //your inputs
</form>

In your javascript:

document.querySelector('#from1').onsubmit = function(e){

    $flag = $(this).attr('data-flag');

    if($flag==0){
        e.preventDefault(); //to prevent submitting

        swal({
            title: "Are you sure?",
            text: "You will not be able to recover this imaginary file!",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: '#DD6B55',
            confirmButtonText: 'Yes, I am sure!',
            cancelButtonText: "No, cancel it!",
            closeOnConfirm: false,
            closeOnCancel: false
         },
         function(isConfirm){

           if (isConfirm){
                swal("Shortlisted!", "Candidates are successfully shortlisted!", "success");

                //update the data-flag to 1 (as true), to submit
                $('#from1').attr('data-flag', '1');
                $('#from1').submit();
            } else {
                swal("Cancelled", "Your imaginary file is safe :)", "error"); 
            }
         });
    }

    return true;
});
schutte
  • 1,949
  • 7
  • 25
  • 45
3

inside your save button click add this code :

$("#btnSave").click(function (e) {
  e.preventDefault();
  swal("Are you sure?", {
    buttons: {
      yes: {
        text: "Yes",
        value: "yes"
      },
      no: {
        text: "No",
        value: "no"
      }
    }
  }).then((value) => {
    if (value === "yes") {
      // Add Your Custom Code for CRUD
    }
    return false;
  });
});
yaya
  • 7,675
  • 1
  • 39
  • 38
Ghadir Farzaneh
  • 429
  • 5
  • 6
1

check confirm or cancel pressed:

     swal2.fire({
            title: 'Your Title',
            input: 'textarea',
            inputAttributes: {
                autocapitalize: 'off'
            },
            showCancelButton: true,
            confirmButtonText: 'ok',
            cancelButtonText: 'cancel',
            allowOutsideClick: false
        }).then((result) => {
            if (result.dismiss !== 'cancel') {

                alert('confirm pressed');
            }
           else
            {
                alert('cancel pressed');

            }
        })

if you using Swal change swal2 to Swal

Hamed B
  • 183
  • 1
  • 12
1

I believe that best way would be explaining both the front end and back end, so will go in a bit depth.

  1. First you have to make a route in your Web.php file.
  2. In your blade file add the below code and change the action attribute to your route location whether you can achieve it by going through route or simply through URL.

Remember don't forget to pass your own route

   <form method="POST" action="{{route('reports.destroy', $dummy->id)}}">
     {{ csrf_field() }}
     {{ method_field('DELETE') }}

    <button type="submit" class="btn btn-danger delete-user">
       Delete {{-- you can add your icon here if you want --}}

    </button> </form>

In the above code, we made the button for the delete and passed: route to our controller in which we have the "delete function".


Now You need to add the below link into your page head tag.

  {{-- links for pop up alert --}}
   <script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script>
   {{-- links for pop up alert --}}

Now add the below code of jQuery.

<script type="text/javascript">

$('.delete-user').click(function(e){
  e.preventDefault();

  Swal.fire({
  title: 'Are you sure?',
  text: "You want to delete record",
  icon: 'warning',
  showCancelButton: true,
  timer: 4000,
  timerProgressBar: true,
  confirmButtonColor: '#3085d6',
  cancelButtonColor: '#d33',
  confirmButtonText: 'Yes, delete it!'
}).then((result) => {
  if (result.isConfirmed) {
    $(e.target).closest('form').submit() // Post the surrounding form

  }
})



});
</script>

You are done, now let me explain the above code: it is getting the class reference named as "delete-user" of your button and when you click on it, the handle will go to your jQuery code and then you can execute it.

Sabaoon Bedar
  • 3,113
  • 2
  • 31
  • 37
1

Sweetalert V1

swal({
    title: "Are you sure?",
    text: "You will not be able to recover this imaginary file!",
    type: "warning",
    showCancelButton: true,
    confirmButtonColor: '#DD6B55',
    confirmButtonText: 'Yes',
    cancelButtonText: "No",
    closeOnConfirm: false,
    closeOnCancel: true
},
function(resp) {
    console.log(resp)
    if (resp) {
        console.log("sssssssssssssiiiii")
    } else {
        console.log('noooooooooooooooooooo')
    }
});

Sweetalert V2

swal({
    title: "Are you sure?",
    text: "Once deleted, you will not be able to recover this imaginary file!",
    icon: "warning",
    buttons: true,
    dangerMode: true,
})
.then((willDelete) => {
    if (willDelete) {
        swal("Poof! Your imaginary file has been deleted!", {
            icon: "success",
        });
    } else {
        swal("Your imaginary file is safe!");
    }
});
Ruzaik Nazeer
  • 474
  • 2
  • 12
Carlos
  • 572
  • 1
  • 5
  • 13
0

This is a late answer but maybe this can help someone. The problem is that you were using an old version, so you have to change the if statements to isConfirm.value === true to validate confirmation and isConfirm.dismiss == "cancel" to cancel confirmation. This will solve the problem.

document.querySelector('#from1').onsubmit = function(e) {

 swal({
    title: "Are you sure?",
    text: "You will not be able to recover this imaginary file!",
    type: "warning",
    showCancelButton: true,
    confirmButtonColor: '#DD6B55',
    confirmButtonText: 'Yes, I am sure!',
    cancelButtonText: "No, cancel it!",
    closeOnConfirm: false,
    closeOnCancel: false
 },
 function(isConfirm){

   if (isConfirm.value === true){
     swal("Shortlisted!", "Candidates are successfully shortlisted!", "success");

    } else if(isConfirm.dismiss === "cancel") {
      swal("Cancelled", "Your imaginary file is safe :)", "error");
         e.preventDefault();
    }
 });
};
Guglie
  • 2,121
  • 1
  • 24
  • 43
0

Click on this Link. I have solved this in angular usingbswal.fire with Ok Cancel buttons , a Boolean value on Ok Cancel click to be updated and timeout after which the Swal will close automatically

Angular Swal.fire() with timeout and ok cancel Button

Zia Khan
  • 188
  • 2
  • 9