Last Updated on April 16, 2024 by Roshan Parihar
To show a delete confirmation message in an alert box, use the confirm()
function of Javascript inside the onclick
attribute.
It can be possible that the users may accidentally click the delete button to remove the content. Confirmation messages help them to stop this by showing a confirmation message. See the examples given below.
Delete Confirmation Message Using onclick Attribute with confirm()
If you want to show a confirmation message on button click, you can use the onclick
attribute inside which uses the confirm()
function of Javascript.
Inside confirm()
function, you can add the text to display to your users in an alert box. The text content in an alert box asks questions to users if they want to delete it or not.
Examples 1
1 |
<a href="url_to_delete.php?action=delete&ID=12" onclick="return confirm('Are you sure you want to delete?')" rel="noopener">Delete</a> |
When you click the button above, you will get an alert message that asks the question of whether you want to delete or not. It contains two buttons The first button is the ‘OK’ button and the second is the ‘Cancel’ button.
If the user wants to delete the content, they can click the ‘OK’ button. The second button is the cancel button to cancel the action of the button.
Define a Function and Call in Onclick Attribute of Button
If you want to display a confirmation message before deleting, you can also create a Javascript function and use the confirm()
inside it. It is useful when you want to perform more actions with the button after deletion.
Now, each time the user clicks on the button element, they will get a confirmation message to proceed by clicking ‘OK’ or stop by clicking ‘Cancel’.
Examples 2
1 2 3 4 5 6 7 8 9 10 |
<button type="button" class="btn btn-primary" onclick="myConfirm()">Delete</button> <script> function myConfirm(){ var result = confirm("Are you really want to delete this item?"); if(result){ alert("hi"); window.location.href = "url_to_delete.php?action=delete&ID=12"; } } </script> |
The button element given above contains no URL. However, when you click the button, it will give you a confirmation message in the alert message box. You can add more actions inside the myConfirm()
to execute on button click.
You May Also Like to Read