Bagaimana cara menampilkan pesan konfirmasi sebelum menghapus?


204

Saya ingin mendapatkan pesan konfirmasi tentang mengklik hapus (ini mungkin tombol atau gambar). Jika pengguna memilih ' Ok' maka hapus sudah dilakukan, lain jika ' Cancel' diklik tidak terjadi apa-apa.

Saya mencoba menggema ini ketika tombol diklik, tetapi menggema hal-hal membuat kotak input dan kotak teks saya kehilangan gaya dan desain mereka.

Jawaban:


330

Tulis ini onclickjika tombol:

var result = confirm("Want to delete?");
if (result) {
    //Logic to delete the item
}

jawaban yang brilian! singkat, tepat dan bekerja secara efisien
John

Bagi orang yang tidak memiliki pengalaman JavaScript, baris kode Anda tidak berarti apa-apa, contohnya terlihat tidak meyakinkan dan membingungkan. Meskipun demikian, ini adalah jawaban yang bagus.
Samuel Ramzan

Saya pikir Anda harus menambahkan beberapa detail pada jawaban Anda. Mengapa Anda memasukkan kode di dalam tombol alih-alih menuliskannya di bagian kepala atau ke file eksternal? Ini adalah fungsi yang sangat umum dan pemrogram mungkin ingin menggunakannya beberapa kali untuk beberapa tombol, saya tidak akan menuliskannya di dalam satu tombol spesifik ...
franz1

286

Anda bisa lebih baik menggunakan sebagai berikut

 <a href="url_to_delete" onclick="return confirm('Are you sure you want to delete this item?');">Delete</a>

2
Ini seharusnya berada di urutan teratas. Sederhana, cepat, efektif. Melakukan pekerjaan dengan sempurna.
DonExo

Sangat berbahaya! Bagaimana jika Javascript telah dimatikan? Atau jika bot laba-laba / pencarian akan membaca halaman ini? Kemudian akan mengikuti semua tautan dan menghapus semuanya! Beberapa plugin browser juga mengikuti semua tautan pada halaman untuk melakukan pra-cache. TIDAK PERNAH melakukannya dengan cara ini! Penghapusan seharusnya tidak pernah menjadi permintaan GET.
Daniele Testa

Itu tidak kalah berbahaya daripada jawaban naik # 1, setiap JavaScript berbahaya jika JavaScript dimatikan. JavaScript yang dinyalakan atau dimatikan adalah pilihan pribadi pengguna, jika JavaScript dimatikan, pengguna harus tahu lebih baik untuk tidak menekan tombol apa pun di situs web mana pun. Selalu ada verifikasi sisi server sebagai alternatif yang bagus.
Samuel Ramzan

53

Ini adalah bagaimana Anda akan melakukannya dengan JavaScript yang tidak mencolok dan pesan konfirmasi ditahan di HTML.

<a href="/delete" class="delete" data-confirm="Are you sure to delete this item?">Delete</a>

Ini adalah vanilla JS murni, kompatibel dengan IE 9+:

var deleteLinks = document.querySelectorAll('.delete');

for (var i = 0; i < deleteLinks.length; i++) {
  deleteLinks[i].addEventListener('click', function(event) {
      event.preventDefault();

      var choice = confirm(this.getAttribute('data-confirm'));

      if (choice) {
        window.location.href = this.getAttribute('href');
      }
  });
}

Lihat dalam aksi: http://codepen.io/anon/pen/NqdKZq


Ini berfungsi dengan baik, tetapi hanya berfungsi untuk tombol pertama. Bagaimana jika kita memiliki 20 atau lebih dari mereka? Terima kasih!
emotalitas

1
Anda benar, itu karena querySelector hanya mencocokkan elemen pertama. Saya telah mengedit jawaban dan bercabang codepen untuk menggunakan querySelectorAll sebagai gantinya.
DevAntoine

Akan keren jika contoh ini diedit juga berfungsi dengan JavaScript dinonaktifkan, misalnya href="https://stackoverflow.com/delete"saya pikir sudah cukup. Atau formulir kirimkan contoh.
Ciro Santilli 郝海东 冠状 病 六四 事件 法轮功

1
@CiroSantilli 巴拿馬 文件 六四 事件 法轮功 Ini sudah terjadi berkat fungsi event.preventDefault (). Anda dapat mengganti hash char dengan url, itu tidak akan dipicu. Tapi, jika JavaScript dinonaktifkan, tautannya akan berfungsi seperti yang diharapkan.
DevAntoine

1
@CiroSantilli 巴拿馬 文件 六四 事件 法轮功 Ini dia;)
DevAntoine

28
function ConfirmDelete()
{
  var x = confirm("Are you sure you want to delete?");
  if (x)
      return true;
  else
    return false;
}


<input type="button" onclick="ConfirmDelete()">

Saya pikir lebih baik hanya memiliki 1 poin kembali. jadi saya lebih suka
jedi

17
Atau adil return confirm("…"). Tidak perlu menetapkan variabel yang boolean dan kemudian bercabang menjadi if / else.
slhck

16

Coba ini. Ini bekerja untuk saya

 <a href="delete_methode_link" onclick="return confirm('Are you sure you want to Remove?');">Remove</a>

1
Cantik dan efisien.
Samuel Ramzan

13

itu sangat sederhana dan satu baris kode

<a href="#" title="delete" class="delete" onclick="return confirm('Are you sure you want to delete this item')">Delete</a>

Sepertinya sudah ada jawaban seperti ini tepat di bawah jawaban yang diterima.
Topi

12

meningkatkan pada user1697128 (karena saya belum bisa mengomentarinya)

<script>
    function ConfirmDelete()
    {
      var x = confirm("Are you sure you want to delete?");
      if (x)
          return true;
      else
        return false;
    }
</script>    

<button Onclick="return ConfirmDelete();" type="submit" name="actiondelete" value="1"><img src="images/action_delete.png" alt="Delete"></button>

akan membatalkan pengiriman formulir jika membatalkan ditekan


8

Saya ingin menawarkan cara saya melakukan ini:

<form action="/route" method="POST">
<input type="hidden" name="_method" value="DELETE"> 
<input type="hidden" name="_token" value="the_token">
<button type="submit" class="btn btn-link" onclick="if (!confirm('Are you sure?')) { return false }"><span>Delete</span></button>
</form>

6

HTML

<input onclick="return myConfirm();" type="submit" name="deleteYear" class="btn btn-danger" value="Delete">

Javascript

<script>
function myConfirm() {
  var result = confirm("Want to delete?");
  if (result==true) {
   return true;
  } else {
   return false;
  }
}


4

HTML:

<a href="#" class="delete" data-confirm="Are you sure to delete this item?">Delete</a>

Menggunakan jQuery:

$('.delete').on("click", function (e) {
    e.preventDefault();

    var choice = confirm($(this).attr('data-confirm'));

    if (choice) {
        window.location.href = $(this).attr('href');
    }
});

Adaptasi jQuery yang bagus untuk jawaban DevAntoines ( stackoverflow.com/a/19973570/1337887 ). Namun, pendekatan yang sedikit lebih umum adalah dengan menggunakan "$ ('A [data-confirm]')" daripada "$ ('. Delete')". Dengan begitu, Anda tidak perlu tombol untuk menghapus kelas, tetapi hanya mengintegrasikan atribut konfirmasi data.
Florian


4
<a href="javascript:;" onClick="if(confirm('Are you sure you want to delete this product')){del_product(id);}else{ }" class="btn btn-xs btn-danger btn-delete" title="Del Product">Delete Product</a>

<!-- language: lang-js -->
<script>
function del_product(id){
    $('.process').css('display','block');
    $('.process').html('<img src="./images/loading.gif">');
    $.ajax({
        'url':'./process.php?action=del_product&id='+id,
        'type':"post",
        success: function(result){
            info=JSON.parse(result);
            if(result.status==1){
                setTimeout(function(){
                    $('.process').hide();
                    $('.tr_'+id).hide();
                },3000);
                setTimeout(function(){
                    $('.process').html(result.notice);
                },1000);
            } else if(result.status==0){
                setTimeout(function(){
                    $('.process').hide();
                },3000);
                setTimeout(function(){
                    $('.process').html(result.notice);
                },1000);
            }
        }
    });
}
</script>


3

Jika Anda tertarik pada beberapa solusi cantik cepat dengan format css selesai, Anda dapat menggunakan SweetAlert

$(function(){
  $(".delete").click(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, delete it!",   
	  	  closeOnConfirm: false 
	  }, 
	  function(isConfirmed){ 
        if(isConfirmed) {
          $(".file").addClass("isDeleted");
          swal("Deleted!", "Your imaginary file has been deleted.", "success"); 
        }
      }
    );
  });
});
html { zoom: 0.7 } /* little "hack" to make example visible in stackoverflow snippet preview */
body > p { font-size: 32px }

.delete { cursor: pointer; color: #00A }
.isDeleted { text-decoration:line-through }
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script src="http://t4t5.github.io/sweetalert/dist/sweetalert-dev.js"></script>
<link rel="stylesheet" href="http://t4t5.github.io/sweetalert/dist/sweetalert.css">

<p class="file">File 1 <span class="delete">(delete)</span></p>


2

untuk mengatur pesan konformasi ketika Anda menghapus sesuatu di php & mysql ...

gunakan kode skrip ini:

<script>
    function Conform_Delete()
    {
       return conform("Are You Sure Want to Delete?");
    }
</script>

gunakan kode html ini:

<a onclick="return Conform_Delete()" href="#">delete</a>

2
var txt;
var r = confirm("Press a button!");
if (r == true) {
   txt = "You pressed OK!";
} else {
   txt = "You pressed Cancel!";
}

var txt;
var r = confirm("Press a button!");
if (r == true) {
    txt = "You pressed OK!";
} else {
    txt = "You pressed Cancel!";
}


1

Menggunakan jQuery:

$(".delete-link").on("click", null, function(){
        return confirm("Are you sure?");
    });

1

Saya tahu ini sudah tua, tetapi saya membutuhkan jawaban dan bukan ini tetapi jawaban alpesh bekerja untuk saya dan ingin berbagi dengan orang-orang yang mungkin memiliki masalah yang sama.

<script>    
function confirmDelete(url) {
    if (confirm("Are you sure you want to delete this?")) {
        window.open(url);
    } else {
        false;
    }       
}
</script>

Versi normal:

<input type="button" name="delete" value="Delete" onClick="confirmDelete('delete.php?id=123&title=Hello')">

Versi PHP saya:

$deleteUrl = "delete.php?id=" .$id. "&title=" .$title;
echo "<input type=\"button\" name=\"delete\" value=\"Delete\" onClick=\"confirmDelete('" .$deleteUrl. "')\"/>";

Ini mungkin bukan cara yang benar untuk melakukannya secara publik tetapi ini berhasil bagi saya di situs pribadi. :)


1

Sangat sederhana

function archiveRemove(any) {
    var click = $(any);
    var id = click.attr("id");
    swal.fire({
        title: 'Are you sure !',
           text: "?????",
           type: 'warning',
           showCancelButton: true,
           confirmButtonColor: '#3085d6',
           cancelButtonColor: '#d33',
           confirmButtonText: 'yes!',
           cancelButtonText: 'no'
    }).then(function (success) {
        if (success) {
            $('a[id="' + id + '"]').parents(".archiveItem").submit();
        }
    })
}

0
function del_confirm(msg,url)
        {
            if(confirm(msg))
            {
                window.location.href=url
            }
            else
            {
                false;
            }

        }



<a  onclick="del_confirm('Are you Sure want to delete this record?','<filename>.php?action=delete&id=<?<id> >')"href="#"></a>

0
<SCRIPT LANGUAGE="javascript">
function Del()
{
var r=confirm("Are you sure?")
if(r==true){return href;}else{return false;}
}
</SCRIPT>

tautan Anda untuk itu:

<a href='edit_post.php?id=$myrow[id]'> Delete</a>

0

Handler onclick harus mengembalikan false setelah panggilan fungsi. Untuk misalnya.

onclick="ConfirmDelete(); return false;">


0

Saya pikir solusi sederhana yang tidak mencolok adalah:

Tautan:

<a href="http://link_to_go_to_on_success" class="delete">Delete</a>

Javascript:

$('.delete').click(function () {
    return confirm("Are you sure?");
});

0
<a href="javascript:;" onClick="if(confirm('Are you sure you want to delete this product')){del_product(id);}else{ }" class="btn btn-xs btn-danger btn-delete" title="Del Product">Delete Product</a>


function del_product(id){
    $('.process').css('display','block');
    $('.process').html('<img src="./images/loading.gif">');
    $.ajax({
        'url':'./process.php?action=del_product&id='+id,
        'type':"post",
        success: function(result){
            info=JSON.parse(result);
            if(result.status==1){
            setTimeout(function(){
                    $('.process').hide();
                    $('.tr_'+id).hide();
                },3000);
                setTimeout(function(){
                    $('.process').html(result.notice);
                },1000);
            }else if(result.status==0){
                setTimeout(function(){
                    $('.process').hide();
                },3000);
                setTimeout(function(){
                    $('.process').html(result.notice);
                },1000);

                }
            }
        });
}

0

Berikut adalah contoh sederhana lain di JS murni menggunakan className dan acara mengikat untuk itu.

var eraseable =  document.getElementsByClassName("eraseable");

for (var i = 0; i < eraseable.length; i++) {
    eraseable[i].addEventListener('click', delFunction, false); //bind delFunction on click to eraseables
}

function delFunction(){        
     var msg = confirm("Are you sure?");      
     if (msg == true) { 
        this.remove(); //remove the clicked element if confirmed
    }   
  };
<button class="eraseable">
<img class="eraseable" src="http://zelcs.com/wp-content/uploads/2013/02/stackoverflow-logo-dumpster.jpg" style="width:100px;height:auto;">
Delete me</button>

<button class="eraseable">
<img class="eraseable" src="http://zelcs.com/wp-content/uploads/2013/02/stackoverflow-logo-dumpster.jpg" style="width:100px;height:auto;">
Delete me</button>

<button class="eraseable">
<img class="eraseable" src="http://zelcs.com/wp-content/uploads/2013/02/stackoverflow-logo-dumpster.jpg" style="width:100px;height:auto;">
Delete me</button>


0
<script>
function deleteItem()
{
   var resp = confirm("Do you want to delete this item???");
   if (resp == true) {
      //do something
   } 
   else {
      //do something
   }
}
</script>

panggil fungsi ini menggunakan onClick


0

Untuk "konfirmasi pesan tentang penghapusan" gunakan:

                       $.ajax({
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        url: "Searching.aspx/Delete_Student_Data",
                        data: "{'StudentID': '" + studentID + "'}",
                        dataType: "json",
                        success: function (data) {
                            alert("Delete StudentID Successfully");
                            return true;
                        }

0

Angularjs Dengan Contoh Hapus Javascript

kode html

<button ng-click="ConfirmDelete(single_play.play_id)" type="submit" name="actiondelete" value="1"><img src="images/remove.png" alt="Delete"></button>

"single_play.play_id" adalah variabel angularjs misalkan Anda ingin melewatkan parameter apa pun selama tindakan penghapusan

Kode angular di dalam modul aplikasi

$scope.ConfirmDelete = function(yy)
        {
            var x = confirm("Are you sure you want to delete?");
            if (x) {
             // Action for press ok
                $http({
                method : 'POST',
                url : 'sample.php',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                data: $.param({ delete_play_id : yy})
                }).then(function (response) { 
                $scope.message = response.data;
                });
            }
            else {
             //Action for cancel
                return false;
            }
        } 

0

Jauh lebih sulit untuk melakukannya untuk kotak pilihan. Ini solusinya:

<select onchange="if (this.value == 'delete' && !confirm('THIS ACTION WILL DELETE IT!\n\nAre you sure?')){this.value=''}">
    <option value=''> &nbsp; </option>
    <option value="delete">Delete Everything</option>
</select>

0

Saya menggunakan cara ini (dalam laravel) -

<form id="delete-{{$category->id}}" action="{{route('category.destroy',$category->id)}}" style="display: none;" method="POST">
 @csrf
 @method('DELETE')
</form>

<a href="#" onclick="if (confirm('Are you sure want to delete this item?')) {
           event.preventDefault();
           document.getElementById('delete-{{$category->id}}').submit();
         }else{
           event.preventDefault();
         }">
  <i class="fa fa-trash"></i>
</a>
Dengan menggunakan situs kami, Anda mengakui telah membaca dan memahami Kebijakan Cookie dan Kebijakan Privasi kami.
Licensed under cc by-sa 3.0 with attribution required.