Django Removal Confirmation

I have a trash can icon for a delete button on a Django site.

This is only an anchor tag with the tag inside, which has its own href set to the delete view, passing the identifier of the model element.

It works fine, but I want to create a popup dialog that asks for confirmation before uninstalling.

I have seen several ways to do this, but they all require that it be entered instead of an anchor.

I also need to do this work on touch devices.

How can I change it to an input element and save the icon as a button, and not show the submit button. And how can I get a dialog for a popup and when the "Yes" button is clicked, pass the correct URL and ID to submit?

Any advice would be highly appreciated.

+4
source share
2 answers

The easiest way is to add a confirmation request:

<a ... onclick="return confirm('Are you sure you want to delete this?')">Delete</a>

But you should not do inline javascript, so try to add a class and distract it. Here it is with jquery:

<a class="confirm-delete" ...>Delete</a>
$(document).on('click', '.confirm-delete', function(){
    return confirm('Are you sure you want to delete this?');
})
+6
source

Let it be your anchor tag:

<a class="icon-trash" id="delete-object" data-object-id="{{ object.id }}">Delete</a>

Notice what we have object.idwith the attribute. We will need this in the javascript part.

And you can write something like this at the bottom of the page before the tag body:

UPDATE WITH SNIPPET

Here you can try the demo. it should work when you put the code right before the tag body:

var elm = document.getElementById('delete-object');
var objectID = elm.getAttribute('data-object-id');
var resultDiv = document.getElementById('result');
elm.addEventListener('click', function() {
  var ask = confirm('r u sure?');
  if (ask && objectID) {
    var r = "Page will be redirected to </object/delete/" + objectID + "/>";
    resultDiv.textContent = r;
  } else {
    resultDiv.textContent = "User cancelled the dialog box...";
  }
  return false;
});
.delete-link {
  background-color: red;
  color: white;
  border: 1px solid white;
  cursor: pointer;
  padding: 3px;
}
#result {
  margin: 20px;
  padding: 10px;
  border: 1px solid orange;
}
<a class="delete-link" id="delete-object" data-object-id="3">Delete</a>
<div id="result"></div>
Run codeHide result
+4
source

All Articles