จะแสดงข้อความยืนยันก่อนลบได้อย่างไร?


204

ฉันต้องการรับข้อความยืนยันเมื่อคลิกลบ (อาจเป็นปุ่มหรือรูปภาพ) หากผู้ใช้เลือก ' Ok' แล้วการลบจะเสร็จสิ้นมิฉะนั้นถ้า ' Cancel' ถูกคลิกไม่มีอะไรเกิดขึ้น

ฉันลองทำเสียงสะท้อนนี้เมื่อคลิกปุ่ม แต่สิ่งที่สะท้อนทำให้กล่องอินพุตและกล่องข้อความของฉันขาดสไตล์และการออกแบบ

คำตอบ:


330

เขียนสิ่งนี้ในonclickกรณีที่มีปุ่ม:

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

คำตอบที่ยอดเยี่ยม! สั้นแม่นยำและทำงานอย่างมีประสิทธิภาพ
จอห์น

สำหรับผู้ที่ไม่มีประสบการณ์ JavaScript บรรทัดโค้ดของคุณไม่มีความหมายตัวอย่างจะดูไม่ลงรอยกันและสับสน อย่างไรก็ตามมันเป็นคำตอบที่ดี
ซามูเอล Ramzan

ฉันคิดว่าคุณควรเพิ่มรายละเอียดในคำตอบของคุณ ทำไมคุณถึงใส่รหัสข้างในปุ่มแทนที่จะเขียนมันในส่วนหัวหรือลงในไฟล์ภายนอก? นี่เป็นฟังก์ชั่นทั่วไปมากและโปรแกรมเมอร์อาจต้องการใช้มันหลาย ๆ ครั้งสำหรับหลาย ๆ ปุ่มฉันจะไม่เขียนมันภายในปุ่มเดียว ...
franz1

285

คุณสามารถใช้งานได้ดีขึ้นดังต่อไปนี้

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

2
นี่ควรจะเป็นทางขึ้นในหัวข้อ ง่ายรวดเร็วมีประสิทธิภาพ ทำงานได้อย่างสมบูรณ์แบบ
DonExo

อันตรายมาก! จะทำอย่างไรถ้า Javascript ถูกปิด หรือถ้าแมงมุม / บอทการค้นหาจะอ่านหน้านี้? จากนั้นจะติดตามลิงก์ทั้งหมดและลบทุกอย่าง! ปลั๊กอินของเบราว์เซอร์บางตัวจะติดตามลิงก์ทั้งหมดในหน้าเว็บเพื่อแคชล่วงหน้า อย่าทำเช่นนี้! การลบไม่ควรเป็นคำขอ GET
Daniele Testa

มันจะไม่อันตรายน้อยไปกว่าคำตอบที่เฟื่องฟูอันดับที่ 1 จาวาสคริปต์ใด ๆ ที่เป็นอันตรายหาก JavaScript ถูกปิด JavaScript กำลังเปิดหรือปิดเป็นตัวเลือกส่วนบุคคลของผู้ใช้หาก JavaScript ถูกปิดผู้ใช้ควรรู้ดีว่าอย่ากดปุ่มใด ๆ บนเว็บไซต์ใด ๆ มีการตรวจสอบด้านเซิร์ฟเวอร์เสมอเป็นทางเลือกที่ยอดเยี่ยม
ซามูเอล Ramzan

53

นี่คือวิธีที่คุณจะทำกับ JavaScript ที่ไม่สร้างความรำคาญและข้อความยืนยันที่ถูกระงับใน HTML

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

นี่คือวานิลลาบริสุทธิ์ JS เข้ากันได้กับ 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');
      }
  });
}

ดูการทำงาน: http://codepen.io/anon/pen/NqdKZq


มันทำงานได้อย่างสมบูรณ์แบบ แต่ใช้ได้กับปุ่มแรกเท่านั้น ถ้าเรามี 20 คนหรือมากกว่านั้นล่ะ? ขอบคุณ!
สมจริง

1
คุณพูดถูกเนื่องจากการเลือกตัวเลือกที่ตรงกับองค์ประกอบแรกเท่านั้น ฉันได้แก้ไขคำตอบและแยก codepen ให้ใช้ querySelectorAll แทน
DevAntoine

จะเย็นถ้าตัวอย่างนี้ถูกแก้ไขยังทำงานกับ JavaScript พิการเช่นhref="https://stackoverflow.com/delete"จะเพียงพอที่ผมคิดว่า หรือแบบฟอร์มส่งตัวอย่าง
Ciro Santilli 郝海东冠状病六四事件法轮功

1
@CiroSantilli 巴拿馬文件六四事件法轮功เป็นกรณีที่ต้องขอบคุณฟังก์ชัน event.preventDefault () คุณสามารถแทนที่ hash char ด้วย url มันจะไม่ถูกทริกเกอร์ แต่ถ้าปิดการใช้งานจาวาสคริปต์ลิงค์จะทำงานได้ตามที่คาดไว้
DevAntoine

1
@CiroSantilli 法轮功文件六四事件法轮功ไปเลย;)
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()">

ฉันคิดว่ามันจะดีกว่าถ้ามีจุดกลับไป 1 จุดเท่านั้น ดังนั้นฉันจึงชอบ
เจได

17
return confirm("…")หรือเพียงแค่ ไม่จำเป็นต้องกำหนดตัวแปรที่เป็นบูลีนแล้วแยกไปที่ if / else
slhck


13

มันง่ายมากและโค้ดหนึ่งบรรทัด

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

ดูเหมือนว่ามีคำตอบอยู่ด้านล่างของคำตอบที่ยอมรับแล้ว
หมวก

12

ปรับปรุงใน user1697128 (เพราะฉันยังไม่สามารถแสดงความคิดเห็นได้)

<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>

จะยกเลิกการส่งแบบฟอร์มหากยกเลิกถูกกด


8

ฉันต้องการเสนอวิธีที่ฉันทำ:

<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">

จาวาสคริ

<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>

ใช้ jQuery:

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

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

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

การปรับตัว jQuery ที่ดีของคำตอบ DevAntoines ( stackoverflow.com/a/19973570/1337887 ) อย่างไรก็ตามวิธีการทั่วไปที่กว้างกว่าเล็กน้อยคือใช้ "$ ('[ยืนยันข้อมูลข้อมูล]')" แทนที่จะเป็น "$ ('. ลบ')" ด้วยวิธีนี้คุณไม่จำเป็นต้องใช้ปุ่มในการลบคลาส แต่เพียงแค่รวมคุณลักษณะการยืนยันข้อมูล
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

หากคุณสนใจวิธีแก้ปัญหาอย่างรวดเร็วด้วยรูปแบบ css ที่ทำคุณสามารถใช้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

การตั้งค่าข้อความโครงสร้างเมื่อคุณลบบางสิ่งใน php & mysql ...

ใช้รหัสสคริปต์นี้:

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

ใช้รหัส html นี้:

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



1

ฉันรู้ว่านี่เก่า แต่ฉันต้องการคำตอบไม่ใช่คำตอบเหล่านี้ แต่คำตอบของalpeshเหมาะกับฉันและต้องการแบ่งปันกับผู้คนที่อาจมีปัญหาเดียวกัน

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

รุ่นปกติ:

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

เวอร์ชั่น PHP ของฉัน:

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

นี่อาจไม่ใช่วิธีที่ถูกต้องในการเผยแพร่ต่อสาธารณะ แต่วิธีนี้ใช้ได้สำหรับฉันในเว็บไซต์ส่วนตัว :)


1

มันง่ายมาก

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>

ลิงก์ของคุณ:

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

0

ตัวจัดการ onclick ควรกลับเท็จหลังจากการเรียกใช้ฟังก์ชัน สำหรับเช่น

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


0

ฉันคิดว่าทางออกที่ไม่เป็นการรบกวนที่ง่ายที่สุดคือ:

Link:

<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

นี่เป็นอีกตัวอย่างง่ายๆใน pure JS โดยใช้ className และ event binding

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>

เรียกใช้ฟังก์ชันนี้โดยใช้ onClick


0

สำหรับการใช้ "ข้อความยืนยันการลบ":

                       $.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 พร้อม Javascript Delete ตัวอย่าง

รหัส 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" เป็นตัวแปรเชิงมุมใด ๆ สมมติว่าคุณต้องการผ่านพารามิเตอร์ใด ๆ ในระหว่างการดำเนินการลบ

โค้ด Angularjs ภายในโมดูลแอพ

$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

มันยากมากที่จะทำเพื่อเลือกกล่องตัวเลือก นี่คือทางออก:

<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

ฉันใช้วิธีนี้ (เป็น 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>
โดยการใช้ไซต์ของเรา หมายความว่าคุณได้อ่านและทำความเข้าใจนโยบายคุกกี้และนโยบายความเป็นส่วนตัวของเราแล้ว
Licensed under cc by-sa 3.0 with attribution required.