[javascript] How to show a confirm message before delete?

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.

This question is related to javascript html

The answer is


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>

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>

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

var x = confirm("Are you sure you want to send sms?");
if (x)
    return true;
else
    return false;  

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

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

will cancel form submission if cancel is pressed


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>

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

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

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


<form onsubmit="return confirm('Are you sure?');" />

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


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. :)


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


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

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

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

Try this. It works for me

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

<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


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>

Using jQuery:

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

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>

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


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


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

                }
            }
        });
}

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>

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

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

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

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


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


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

If you are interested in some quick pretty solution with css format done, you can use SweetAlert

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


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>


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

_x000D_
_x000D_
var eraseable =  document.getElementsByClassName("eraseable");_x000D_
_x000D_
for (var i = 0; i < eraseable.length; i++) {_x000D_
    eraseable[i].addEventListener('click', delFunction, false); //bind delFunction on click to eraseables_x000D_
}_x000D_
_x000D_
function delFunction(){        _x000D_
     var msg = confirm("Are you sure?");      _x000D_
     if (msg == true) { _x000D_
        this.remove(); //remove the clicked element if confirmed_x000D_
    }   _x000D_
  };
_x000D_
<button class="eraseable">_x000D_
<img class="eraseable" src="http://zelcs.com/wp-content/uploads/2013/02/stackoverflow-logo-dumpster.jpg" style="width:100px;height:auto;">_x000D_
Delete me</button>_x000D_
_x000D_
<button class="eraseable">_x000D_
<img class="eraseable" src="http://zelcs.com/wp-content/uploads/2013/02/stackoverflow-logo-dumpster.jpg" style="width:100px;height:auto;">_x000D_
Delete me</button>_x000D_
_x000D_
<button class="eraseable">_x000D_
<img class="eraseable" src="http://zelcs.com/wp-content/uploads/2013/02/stackoverflow-logo-dumpster.jpg" style="width:100px;height:auto;">_x000D_
Delete me</button>
_x000D_
_x000D_
_x000D_


It can be simplify to this:

<button onclick="return confirm('Are you sure you want to delete?');" />

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