Return confirm cancel button not working

11,957

Solution 1

You can validade the confirm box outside of html element, in a function and, call this function on 'onclick' event. Like this:

<a href="somePage" onclick="return myFunction()">My link</a>

function myFunction() {
    if (confirm("Confirm message")) {
       // do stuff
    } else {
      return false;
    }
}

Solution 2

Adding event.preventDefault(); fixed it.

Here is an example:

console.log('Validating...');

function confirm_delete(){
var txt;
var r = confirm("Are you sure you want to delete?");
if (r == true) {
    txt = "You pressed OK!";
} else {
    txt = "You pressed Cancel!";
    event.preventDefault();
}
console.log(txt);
}
Share:
11,957

Related videos on Youtube

Tommie
Author by

Tommie

Webdeveloper from the netherlands.

Updated on October 12, 2022

Comments

  • Tommie
    Tommie over 1 year

    I have this link in twig :

    <a href="{{ path('relation-delete', {'id': c.getCustomerId}) }}" 
       onclick="return confirm('{% trans %}relation.delete{% endtrans %}');"
       class="tip" data-original-title="Verwijder klant {{ c.getCustomerName }}">
    

    The HTML in the source :

    <a href="/app_dev.php/projects/delete/1" class="tip" 
      data-original-title="Verwijder project Lantaarn plaatsen" 
      onclick="return confirm('Verwijderen');">
    
    <button class="btn btn-danger"><i class="fa fa-times fa-fw"></i></button></a>`
    

    the onlick confirm cancel button doesn't cancel the action but just keeps going. Somebody knows what's wrong with this return confirm ?

  • Tommie
    Tommie over 9 years
    It turns out this was causing the problem in a other javascript file: $("a").click(function(e) { e.preventDefault(); location.href = $(this).attr("href"); });