Shyam K
Shyam K

Reputation: 2908

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.

Upvotes: 256

Views: 960203

Answers (30)

Jaxx0rr
Jaxx0rr

Reputation: 597

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

Upvotes: 16

user1697128
user1697128

Reputation: 385

function ConfirmDelete()
{
  return confirm("Are you sure you want to delete?");
}


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

Upvotes: 35

Buksy
Buksy

Reputation: 12218

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>

Upvotes: 7

Ernestyno
Ernestyno

Reputation: 857

It can be simplify to this:

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

Upvotes: 9

Mohammed Muzammil
Mohammed Muzammil

Reputation: 704

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>

Upvotes: 29

Shamsul Huda
Shamsul Huda

Reputation: 163

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>

Upvotes: 0

Masoud
Masoud

Reputation: 1245

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

Upvotes: 1

Nazmul Haque
Nazmul Haque

Reputation: 868

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

Upvotes: 7

Gauravbhai Daxini
Gauravbhai Daxini

Reputation: 2190

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

Upvotes: 2

Tarik
Tarik

Reputation: 4536

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>

Upvotes: 0

zeros-and-ones
zeros-and-ones

Reputation: 4438

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>

Upvotes: 12

himos
himos

Reputation: 41

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

Upvotes: 4

user7641341
user7641341

Reputation: 209

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

Upvotes: -1

Rijo
Rijo

Reputation: 3043

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

Upvotes: 0

Arvind Upadhyay.
Arvind Upadhyay.

Reputation: 1

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

Upvotes: 0

pvrforpranavvr
pvrforpranavvr

Reputation: 2938

<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

Upvotes: 0

Arun Sharma
Arun Sharma

Reputation: 1331

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>

Upvotes: 0

DevAntoine
DevAntoine

Reputation: 1942

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

Upvotes: 63

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

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

Upvotes: 4

ashik
ashik

Reputation: 119

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>

Upvotes: 2

KingRider
KingRider

Reputation: 2257

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

Upvotes: 3

Shuhad zaman
Shuhad zaman

Reputation: 3390

Try this. It works for me

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

Upvotes: 21

xahoigiaitri
xahoigiaitri

Reputation: 51

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

                }
            }
        });
}

Upvotes: 0

Cookalino
Cookalino

Reputation: 1619

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

Upvotes: 0

Ved
Ved

Reputation: 8757

Write this in onclick event of the button:

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

Upvotes: 402

emotality
emotality

Reputation: 13035

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

Upvotes: 1

julionc
julionc

Reputation: 359

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

Upvotes: 4

Amit
Amit

Reputation: 1

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

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

Upvotes: 0

Raghav Rach
Raghav Rach

Reputation: 4935

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>

Upvotes: 397

Azat
Azat

Reputation: 1

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

Upvotes: 0

Related Questions