250

I want to get a confirm message on clicking delete (this maybe a button or an image). If the user selects 'Ok' then delete is done, else if 'Cancel' is clicked nothing happens.

I tried echoing this when the button was clicked, but echoing stuff makes my input boxes and text boxes lose their styles and design.

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
Shyam K
  • 2,848
  • 2
  • 19
  • 24

33 Answers33

400

Write this in onclick event of the button:

var result = confirm("Want to delete?");
if (result) {
    //Logic to delete the item
}
Ved
  • 8,577
  • 7
  • 36
  • 69
  • 1
    brilliant answer! short,precise and works efficiently – BLESSING Feb 21 '20 at 08:47
  • 2
    To any non experiences JavaScript person, your code lines mean nothing, the example looks inconclusive and confusing. Nonetheless, it's a good answer. – Samuel Ramzan Jun 22 '20 at 13:20
  • 1
    I think you should add some details to your answer. Why do you insert the code inside the button instead of writing it in the head section or into an external file? This is a very generic function and the programmer may want to use it several times for several buttons, I wouldn't write it inside a single specific button... – franz1 Jun 22 '20 at 17:04
  • @franz1 You're missundertanding what is shown in the answer, this code is'nt inside a button, this is code which can be executed inside a fuction and the function be called with anyone button at onclick="myFunctionThatDeletesMyItem()". The answer is pretty simple and effective! – Cristianjs19 Feb 25 '21 at 04:13
  • 1
    In react you have to use window.confirm() instead of just confirm() – Vikram Ray Oct 07 '21 at 08:34
395

You can better use as follows

 <a href="url_to_delete" onclick="return confirm('Are you sure you want to delete this item?');">Delete</a>
Besnik
  • 6,469
  • 1
  • 31
  • 33
Raghav Rach
  • 4,875
  • 2
  • 16
  • 16
  • 6
    This should be way up in the thread. Simple, fast, effective. Does the job just perfectly. – Donald Mar 22 '20 at 21:39
  • 1
    Very dangerous! What if Javascript has been turned off? Or if a spider/search bot would read this page? It would then follow all the links and delete everything! Some browser plugins also follows all the links on a page to pre-cache it. NEVER do it this way! Deletes should never be a GET request. – Daniele Testa May 21 '20 at 14:50
  • 1
    It's not less dangerous than the #1 up boated answer, any JavaScript is dangerous if JavaScript is turned off. JavaScript being turned on or off is a user's personal choice, if JavaScript is turned off, the user should know better not to push any buttons on any website. There's always server side verification as a wonderful alternative. – Samuel Ramzan Jun 22 '20 at 13:25
  • 2
    In theory, if you're managing resources you're behind some authentication and none of these pages are crawled by bots. – Kyle Smith Mar 04 '21 at 13:17
63

This is how you would do it with unobtrusive JavaScript and the confirm message being hold in the HTML.

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

This is pure vanilla JS, compatible with 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');
      }
  });
}

See it in action: http://codepen.io/anon/pen/NqdKZq

DevAntoine
  • 1,932
  • 19
  • 24
  • This works perfectly, but only works for the first button. What if we have like 20 or more of them? Thanks! – emotality Feb 07 '15 at 22:39
  • 1
    You are right, it's because of querySelector matching only the first element. I've edited the answer and forked the codepen to use querySelectorAll instead. – DevAntoine May 28 '15 at 11:28
  • Would be cool if this example were edited to also work with JavaScript disabled, e.g. `href="/delete"` would be enough I think. Or a form submit example. – Ciro Santilli OurBigBook.com May 10 '16 at 09:20
  • 1
    @CiroSantilli巴拿馬文件六四事件法轮功 It's already the case thanks to the event.preventDefault() function. You can replace the hash char with a url, it won't be triggered. But, if JavaScript is disabled the link will work as expected. – DevAntoine May 13 '16 at 08:18
  • Just just what I meant: on the example, replace the hash with an URL `href="/delete"`, as it is what most people should use. Hadn't edited because was not 100% ;-) – Ciro Santilli OurBigBook.com May 13 '16 at 08:26
  • 2
    @CiroSantilli巴拿馬文件六四事件法轮功 Here you go ;) – DevAntoine May 13 '16 at 08:58
  • Nice! But I just have the habit of keeping the 'class' for the looks, and 'id' for functionality... – Makan Jun 23 '17 at 07:23
  • @DevAntoine So? All the more reason to not use classes for functionality. eh? – Makan Jul 03 '17 at 23:26
  • The pen doesn't work. I can click the links all I want, but nothing happens. – Frank Conijn - Support Ukraine Aug 05 '21 at 01:19
  • @FrankConijn there's currently an issue with `confirm` and some other functions on Codepen: "A different origin subframe tried to create a JavaScript dialog. This is no longer allowed and was blocked. See https://www.chromestatus.com/feature/5148698084376576 for more details." – DevAntoine Aug 20 '21 at 09:07
35
function ConfirmDelete()
{
  return confirm("Are you sure you want to delete?");
}


<input type="button" onclick="ConfirmDelete()">
andi
  • 311
  • 1
  • 16
user1697128
  • 385
  • 4
  • 2
  • I think that it's better to have only 1 return point. so i prefer – jedi Nov 06 '13 at 12:40
  • 19
    Or just `return confirm("…")`. There's no need to assign a variable that is boolean and then branch into if/else. – slhck Feb 04 '14 at 11:38
28

it is very simple and one line of code

<a href="#" title="delete" class="delete" onclick="return confirm('Are you sure you want to delete this item')">Delete</a>
zeros-and-ones
  • 4,227
  • 6
  • 35
  • 54
21

Try this. It works for me

 <a href="delete_methode_link" onclick="return confirm('Are you sure you want to Remove?');">Remove</a>
MattAllegro
  • 6,455
  • 5
  • 45
  • 52
Shuhad zaman
  • 3,156
  • 32
  • 32
16

improving on user1697128 (because I cant yet comment on it)

<script>
    function ConfirmDelete()
    {
      return confirm("Are you sure you want to delete?");
    }
</script>    
    
<button Onclick="return ConfirmDelete();" type="submit" name="actiondelete" value="1"><img src="images/action_delete.png" alt="Delete"></button>

will cancel form submission if cancel is pressed

andi
  • 311
  • 1
  • 16
Jaxx0rr
  • 507
  • 4
  • 7
12

I would like to offer the way I do this:

<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>
zeros-and-ones
  • 4,227
  • 6
  • 35
  • 54
  • 1
    This is nice. I already had a form set up with multiple buttons and I only needed to add the `onclick="if (!confirm('Are you sure?')) { return false }"` to my existing and it worked. Thank you. – Anthony Petrillo Jul 13 '20 at 21:59
8

It can be simplify to this:

<button onclick="return confirm('Are you sure you want to delete?');" />
Ernestyno
  • 797
  • 1
  • 10
  • 16
7

If you are interested in some quick pretty solution with css format done, you can use 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 
      }).then(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="https://unpkg.com/sweetalert/dist/sweetalert.min.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>
Buksy
  • 11,571
  • 9
  • 62
  • 69
7

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

Nazmul Haque
  • 720
  • 8
  • 13
4

HTML:

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

Using jQuery:

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

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

    if (choice) {
        window.location.href = $(this).attr('href');
    }
});
julionc
  • 349
  • 1
  • 4
  • A good jQuery adaption of DevAntoines answer (http://stackoverflow.com/a/19973570/1337887). However, a slightly more generalized approach would be to use "$('A[data-confirm]')" instead of "$('.delete')". That way, you don't need the buttons to have a delete class, but instead just integrate the data-confirm attribute. – Florian Oct 11 '16 at 08:26
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>
himos
  • 41
  • 1
4
<form onsubmit="return confirm('Are you sure?');" />

works well for forms. Form-specific question: JavaScript Form Submit - Confirm or Cancel Submission Dialog Box

Community
  • 1
  • 1
Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
3

Practice

<form name=myform>
<input type=button value="Try it now" 
onClick="if(confirm('Format the hard disk?'))
alert('You are very brave!');
else alert('A wise decision!')">
</form>

Web Original:

http://www.javascripter.net/faq/confirm.htm

MattAllegro
  • 6,455
  • 5
  • 45
  • 52
KingRider
  • 2,140
  • 25
  • 23
2

to set a conformation message when you delete something in php & mysql...

use this script code:

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

use this html code:

<a onclick="return Conform_Delete()" href="#">delete</a>
ashik
  • 119
  • 1
  • 11
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!";
}
Gauravbhai Daxini
  • 2,032
  • 2
  • 22
  • 28
1

Using jQuery:

$(".delete-link").on("click", null, function(){
        return confirm("Are you sure?");
    });
Apeli
  • 509
  • 7
  • 17
1

I know this is old, but I needed an answer and non of these but alpesh's answer worked for me and wanted to share with people that might had the same problem.

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

Normal version:

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

My PHP version:

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

This might not be the correct way of doing it publicly but this worked for me on a private site. :)

emotality
  • 12,795
  • 4
  • 39
  • 60
1

Its very simple

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();
        }
    })
}
Masoud
  • 1,099
  • 1
  • 10
  • 22
1
function confirmDelete()
{
var r=confirm("Are you sure you want to delte this image");
if (r==true)
{
//User Pressed okay. Delete

}
else
{
//user pressed cancel. Do nothing
    }
 }
<img src="deleteicon.png" onclick="confirmDelete()">

You might want to pass some data with confirmDelete to determine which entry is to be deleted

SoWhat
  • 5,564
  • 2
  • 28
  • 59
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>
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
alpesh
  • 9
  • 1
0
<SCRIPT LANGUAGE="javascript">
function Del()
{
var r=confirm("Are you sure?")
if(r==true){return href;}else{return false;}
}
</SCRIPT>

your link for it:

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

The onclick handler should return false after the function call. For eg.

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

dehrg
  • 1,721
  • 14
  • 17
Amit
  • 1
0

I think the simplest unobtrusive solution would be:

Link:

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

Javascript:

$('.delete').click(function () {
    return confirm("Are you sure?");
});
Cookalino
  • 1,559
  • 14
  • 19
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);

                }
            }
        });
}
MattAllegro
  • 6,455
  • 5
  • 45
  • 52
0

Here is another simple example in pure JS using className and binding event to it.

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>
Arun Sharma
  • 1,331
  • 8
  • 11
0
<script>
function deleteItem()
{
   var resp = confirm("Do you want to delete this item???");
   if (resp == true) {
      //do something
   } 
   else {
      //do something
   }
}
</script>

call this function using onClick

René Wolferink
  • 3,558
  • 2
  • 29
  • 43
pvrforpranavvr
  • 2,708
  • 2
  • 24
  • 34
0

For "confirmation message on delete" use:

                       $.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 With Javascript Delete Example

html code

<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" is any angularjs variable suppose you want to pass any parameter during the delete action

Angularjs code inside the app module

$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;
            }
        } 
Rijo
  • 2,963
  • 5
  • 35
  • 62
0

It is much harder to do it for select option boxes. Here is the solution:

<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>
Tarik
  • 4,270
  • 38
  • 35
0

I'm useing this way (in 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>

Shamsul Huda
  • 163
  • 1
  • 9
-1
var x = confirm("Are you sure you want to send sms?");
if (x)
    return true;
else
    return false;  
Nathan Tuggy
  • 2,237
  • 27
  • 30
  • 38
user7641341
  • 169
  • 1
  • 5