Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Link is still navigating even if user hasn't confirmed

Tags:

html

jquery

MY question is that even though I click on the Cancel button in the confirmation, the link still navigates to its destination? How can I stop the link from navigating to the destination if user clicks on cancel in the confirmation box? I only want it to navigate if user clicks on the OK button:

<a id='teachlogout' href='./teacherlogout.php'>Logout</a>
function logoutHandler() {
    if (confirm("You are currently creating an Assessment, are you sure you want to logout?" + "\n" + "(Your current assessment details will be lost)" + "\n")) {
        return true;
    }
}

// logout link
$('#teachlogout').click(function() {
    logoutHandler();
});
like image 789
user1914374 Avatar asked Dec 09 '22 18:12

user1914374


1 Answers

You need to return false or event.preventDefault() if the user cancels the confirm. Try this:

function logoutHandler() {
    return confirm("You are currently creating an Assessment, are you sure you want to logout?" + "\n" + "(Your current assessment details will be lost)" + "\n");
}

// logout link
$('#teachlogout').click(logoutHandler); 
// ^ Shorter version when you only need to call 1 function with no params

Or this:

function logoutHandler(e) {
    if (!confirm("You are currently creating an Assessment, are you sure you want to logout?" + "\n" + "(Your current assessment details will be lost)" + "\n")) {
        e.preventDefault();
    }
}

// logout link
$('#teachlogout').click(function(e) {
    logoutHandler(e);
}); 
like image 155
Rory McCrossan Avatar answered Dec 11 '22 07:12

Rory McCrossan