function executing action even if false

Asked

Viewed 59 times

0

well I’m doing a college job, and has a file listing screen, at the time of deleting I created a button with onclick, I do not understand much of javascript, however following the logic of if Else it should run only the action if it were true, more even if I cancel it runs;

<script>
function apagar(){
var res = confirm("Deseja Apagar a questão ?");
    if (res == false){
        var href = this.href;
    }else{
        alert("Cancelado");
    }
}
</script>
<a href="apagar_questao.php"><button type="button" class="btn btn-danger" id="btn_apagar" onclick="apagar()">Apagar</button></a>

  • In your if condition it should not be if(res == true) nay?

  • any of the two that I place it executes the action, being true or false it executes the href

  • The problem is that you should not put a button inside a link. Link is link, button is button, one should not mix the two things.

1 answer

0


The problem is that you are placing the function in an element that is within a href, ie regardless of the value it is true or false He’ll move on to the next page. What can be done and redirect with window.location. If there is even a need for tag a you can put javascript:void(0) that he directs nowhere.

The code would be like this.

<script type="text/javascript">
function apagar(idRes){
var res = confirm("Deseja Apagar a questão ?");
    if (res){
      window.location = "apagar_questao.php?id="+idRes;
      }else{
       alert("Cancelado");
     }
   }
</script>
<a href="javascript:void(0)"><button type="button" class="btn btn-danger" id="btn_apagar" onclick="apagar(<?php echo $linhas['id'];?>)">Apagar</button></a>

  • <a href="apagar_questao.php? &id=<? php echo $lines['id']? >"> and when I have to get the id ? to send as I should do

  • I’ve modified the answer so you can see how it will look, in which case you can pass the id php via the function parameter on the button. Then in Javascript you concatenate the id with the link.

  • I’ll try here, thanks mt

  • worked perfectly, thank you very much :D, I wish you much success, I could never make that code with the little knowledge I have. A big hug.

  • At first it’s always like this. D but why don’t you do it with submit of a form? and when you check everything you allow it to follow give the submit.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.