danitri
danitri

Reputation: 13

how to add callback into function with javascript?

I want to create function which inside include swall then call that function with another job...

here is my code:

function confirmSwal(ket, callback){
  swal({
    title: ket,
    showCancelButton: true,
    cancelButtonText: 'Batal',
    confirmButtonClass: 'btn-success',
    confirmButtonText: 'Hapus',
    closeOnConfirm: true
  },
  function(){
    callback();
  });
}

$("#hapusBulk").click(function(){
  confirmSwal("Apakah Anda Yakin Hapus Data Terpilih?", function(){
    alert("Asd");
  });
});

but alert doesn't work.. please help..

Upvotes: 0

Views: 367

Answers (3)

Dean
Dean

Reputation: 678

It should be like this.

function confirmSwal(ket, callback){
    swal({
        title: ket,
        showCancelButton: true,
        cancelButtonText: 'Batal',
        confirmButtonClass: 'btn-success',
        confirmButtonText: 'Hapus',
        closeOnConfirm: true
    }, callback
    )}

$("#hapusBulk").click(function(){
    confirmSwal("Apakah Anda Yakin Hapus Data Terpilih?", function(){
        alert("Asd");
    });
});

because of your callback variable is defined as a function, and you don't require to have a function to wrap the callback value.

Upvotes: 2

Shivaji Varma
Shivaji Varma

Reputation: 682

Use then method

Here is the jsbin link with working implementation: https://jsbin.com/tawesufuge/1/edit?html,js,output

function confirmSwal(ket, callback){
  swal({
    title: ket,
    showCancelButton: true,
    cancelButtonText: 'Batal',
    confirmButtonClass: 'btn-success',
    confirmButtonText: 'Hapus',
    closeOnConfirm: true
  }).then(callback);
}


$("#hapusBulk").click(function(){
  confirmSwal("Apakah Anda Yakin Hapus Data Terpilih?", function(){
    alert("Asd");
  });
});
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>

  <button id="hapusBulk">hapusBulk</button>
  
</body>
</html>

Upvotes: 0

elasmai elmehdi
elasmai elmehdi

Reputation: 91

If the swal function accept a callback, you need to change your code to this :

function confirmSwal(ket, callback){
  swal({
    title: ket,
    showCancelButton: true,
    cancelButtonText: 'Batal',
    confirmButtonClass: 'btn-success',
    confirmButtonText: 'Hapus',
    closeOnConfirm: true
  }, callback() );
}

Upvotes: 0

Related Questions