Lucas Rezende
Lucas Rezende

Reputation: 2686

Do nothing when confirmation message is false in Django

I have an URL that passes the ID of a record to a view for this to be deleted. But, I would like to show a confirmation message to the user before deleting the record.

I am trying to do it with Javascript but doesn't work. The message appears but even after clicking "Cancel" Django reloads the page and consequentially deletes the row.

<script type="text/javascript">
    function confirmaExclusao() {
        var resp = confirm("O grupo será excluído permanentemente. Deseja continuar?")
        if (!resp) {
            return false;
        }
    }
</script>

...

<a href="/grupos/remover/{{ grupo.id }}" onclick="confirmaExclusao()"><img src="{{ STATIC_URL }}img/btn_remove_group.png"></a>

Can someone help me on this issue?

Thanks in advance.

Upvotes: 2

Views: 1341

Answers (2)

Ian
Ian

Reputation: 50905

I would NOT recommend doing what the other answerer suggests. All you need to do is change your <a> tag to this:

<a href="/grupos/remover/{{ grupo.id }}" onclick="return confirmaExclusao();">

and then add:

return true;

at the end of your confirmaExclusao function.

The reason this change is needed is because the default behavior of clicking a <a> tag is to execute the "onclick" javascript code, and then execute/follow the "href". If you return false in the onclick, the "href" is not followed. If you return true or don't return anything, the "href" is followed. So in your case, you need to return the result of the function call. In your function, you need to return the result of the confirm(), so technically your function could just be:

<script type="text/javascript">
     function confirmaExclusao() {
        return confirm("O grupo será excluído permanentemente. Deseja continuar?");
    }
</script>

but still make the change to your link tag.

Upvotes: 1

ZnArK
ZnArK

Reputation: 1541

This is because you are operating inside the context of a link. Try taking away the Greg and using window.setlocation() in your code

 <script type="text/javascript"> 
 function confirmaExclusao() { 
    var resp = confirm("O grupo será excluído permanentemente. Deseja continuar?") ;
   if (!resp) { return false; } 
   Window.location(" /grupos/remover/{{ grupo.id }} ");
 } </script>


  <iMG src="..." Onclick="confirmaExclusao()">

Upvotes: 0

Related Questions