How to disable link via Javascript CONFIRM?

Asked

Viewed 44 times

0

I am developing my first web application, being it an account manager to receive and to pay, and I found a difficulty when I came across the need for a Javascript CONFIRM to allow or block the action of quitting an account to pay. I’m using PHP to send some data through the URL so that the application drops the account and returns to the same page with the same search parameters, such as initial and final date, and account status.

<a onclick="confirma()" href="valida_cpagar.php?registro=<?php echo $registro;?>&di=<?php echo $data_inicial; ?>&df=<?php echo $data_final; ?>&st=<?php echo $status; ?>&valor=<?php echo number_format($dado["valor"],2);?>">Baixar</a>

This is the link I’m using. When the information arrives on the page "valida_cpagar.php", the changes are made in the database and through a HEADER, returns the account page to pay with the same parameters, as said above.

I’m trying to use a Javascript function, but obviously it’s wrong, because it doesn’t work.

    function confirma(){
        var conf = confirm("Você confirma a operação?");
        if (conf == true){          
            alert("Conta baixada!");
            location.href="valida_cpagar.php?registro=<?php echo $registro;?>&di=<?php echo $data_inicial; ?>";
        } else {
            alert("Operação cancelada!"); }
        }

I would like that if CONFIRM were true, the account would be downloaded normally, and if it were false, only an ALERT would be displayed and nothing would be done in the database.

I’m a beginner in programming, and everything for me has been new. Thank you to everyone who can help.

2 answers

0

You can change the anchor to:

<a onclick="confirma()" href="javascript:void(0)">Baixar</a>

And let the click do the execution.

0

The natural action of a click on an element <a> is to forward the user to the URL indicated in the attribute href. Therefore, it is natural that the user clicking on the link is redirected to the page valida_cpagar.php.

How you want to avoid natural behavior and control it manually through function confirma, you should inform this to the browser with the instruction preventDefault:

function confirma(event) {
    event.preventDefault();
    // ...
}

With this you inhibit natural behavior, prevailing what you define within the function.

  • 1

    Only for that it is necessary to pass the event in function: onclick="confirma(event)", else the variable event in function confirma(event) { will have no value.

Browser other questions tagged

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