user5065157
user5065157

Reputation:

How to use confirm using sweet alert?

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

Upvotes: 47

Views: 317276

Answers (14)

Sahib Khan
Sahib Khan

Reputation: 602

In the original question the problem is the if condition. It returns an object. Which is always true.

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

    } else {
      swal("Cancelled", "Your imaginary file is safe :)", "error");
    }

when you hit cancel it returns this

{dismiss: 'cancel'}

Upvotes: 0

Sabaoon Bedar
Sabaoon Bedar

Reputation: 3689

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.

Upvotes: 1

Carlos
Carlos

Reputation: 706

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!");
    }
});

Upvotes: 1

Zia Khan
Zia Khan

Reputation: 425

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

Upvotes: 0

Carlos Agelvis
Carlos Agelvis

Reputation: 31

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

Upvotes: 0

Hamed B
Hamed B

Reputation: 313

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

Upvotes: 1

Koen van der Marel
Koen van der Marel

Reputation: 208

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.

Upvotes: 9

Ghadir Farzaneh
Ghadir Farzaneh

Reputation: 458

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

Upvotes: 3

schutte
schutte

Reputation: 2166

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

Upvotes: 3

Moode Osman
Moode Osman

Reputation: 2013

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

Upvotes: 4

dfsq
dfsq

Reputation: 193261

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

Upvotes: 58

Hiran Walawage
Hiran Walawage

Reputation: 2185

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

Upvotes: 3

saka
saka

Reputation: 127

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

Upvotes: 8

Bit_Pulse
Bit_Pulse

Reputation: 356

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

Upvotes: 11

Related Questions