In this tutorial, we will learn how to display a delete confirmation message using JavaScript when we want to delete any data.
A delete confirmation message is most important because if a user clicks the delete button by mistake, then data will be deleted immediately if delete confirmation functionality is not implemented. For prevent this we will use the confirm()
method.
What is JavaScript Confirm Delete?
In Javascript, the confirm()
function is a built-in method that opens a modal dialog box with a custom message and two buttons which is "OK" and "Cancel." If the user clicks "OK," then the function returns true, and if the user clicks "Cancel," then the function returns false.
Syntax
The syntax for the confirm()
function is :
confirm("Are you sure you want to delete this data?");
Example
<!DOCTYPE html>
<html>
<head>
<title>Delete Confirmation Message using JavaScript</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<ul id="myList">
<li>Item 1 <button onclick="deleteItem(this)">Delete</button></li>
<li>Item 2 <button onclick="deleteItem(this)">Delete</button></li>
<li>Item 3 <button onclick="deleteItem(this)">Delete</button></li>
</ul>
<script>
function deleteItem(element) {
var listItem = element.parentNode;
var confirmDelete = confirm("Are you sure you want to delete this item?");
if (confirmDelete) {
listItem.remove();
}
}
</script>
</body>
</html>
Output
Conclusion
Deleting a confirmation message using JavaScript is essential to prevent accidental data loss and improve user experience.
Leave a comment