Javascript confirm yes no dialog is popped up before deleting

Lionsure 2020-06-15 Original by the website

In order to avoid deleting data by mistake, it should not be too troublesome to pop up a confirmation/cancel inquiry dialog(i.e. javascript confirm dialog) before deleting. It cannot be restored after deleting data without mistakes. The data deletion of the website is initiated by the user on the client, so the confirmation/cancel inquiry dialog is popped up by javascript. It pops up the inquiry dialog is the same as that popped up by the Windows system.

There are several ways to pop up a javascript confirm dialog before deleting in javascript. We only introduce a method that is convenient to call, so that it is easy to call in javascript code and html file.

 

1. The method of javascript confirm yes no dialog is popped up

In order to facilitate the call, we encapsulate it into a method(function), the following is the specific code:

function ConfirmBeforeDeleting() {
              if (window.confirm("Are you sure you want to delete?")) {
                     return true;//Sure to return true
              }
              else {
                     return false;//Cancel return false
              }
       }

From the above deletion code, it is the confirm method of windows. The "Are you sure you want to delete?" in brackets is a text that asks the user in the query dialog, which can be modified according to your own requirements. When the user confirms that you want to delete(that is, click the "confirm" button), it returns true; when the user cancels(click the "Cancel" button), return to false.

 

2. Application Example of javascript confirm yes no

If the user selects several product items to be deleted, he(or she) immediately clicks "Delete" and a "Confirm" dialog will be popped up. Only he(or she) selects "Confirm" before deleting, otherwise they will not be deleted. The specific codes are as follows:

<span onclick="DeleteItems()">Delete</span>

function DeleteItems() {
              if (ConfirmBeforeDeleting()) {
                     //Delete operation
                     alert("Delete");
              }
              else {
                     //Cancel back
                     alert("Cancel");
              }
       }

As long as you directly call the ConfirmBeforeDeleting() method before deleting in each javascript method that wants to delete data; when it returns true, perform the delete operation, otherwise the data is not deleted.