Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With jQuery preventDefault() how can you do the default action?

Tags:

jquery

I have the following code:

$('a.confirm').click(function(e) {
    e.preventDefault();
    var answer = confirm("Are you sure?")
    if (answer){
        // do the default action
    } 
});

What code would I have to put in for the default action to be executed if the user confirms?

like image 208
geoffs3310 Avatar asked Nov 24 '10 16:11

geoffs3310


2 Answers

$('a.confirm').click(function(e) {
    var answer = confirm("Are you sure?")
    if (answer){
        // do the default action
    } else {
      e.preventDefault();
    }
});

or

$('a.confirm').click(function(e) {
    var answer = confirm("Are you sure?")
    if (!answer){
      e.preventDefault();
    }
});

or even just

$('a.confirm').click(function(e) {
    return confirm("Are you sure?");
});
like image 66
RoToRa Avatar answered Oct 08 '22 14:10

RoToRa


You can just return confirm("Are you sure?"). That will return true or false, where false prevents the action.

like image 25
Keith Rousseau Avatar answered Oct 08 '22 13:10

Keith Rousseau