7

The following code pops up a confirmation windows when the Delete user link is pressed:

<a href="delete_user.php?id=123" onclick="return confirm('Are you sure?');">Delete user</a>

In this case when the OK button is pressed the link delete_user.php?id=123 will be executed. When the Cancel button is pressed nothing will happened.

I would like to do the same thing with Bootbox.

   <a class="alert" href="list_users.php?id=123">Delete user</a>

    <script src="bootbox.min.js"></script>
        <script>
        $(document).on("click", ".alert", function(e) {
            e.preventDefault();

        bootbox.confirm("Are you sure?", function(result) {

            if (result) {
               // What to do here?
            } else {
               // What to do here?
            }               
        });

        });
    </script>

What to do under if(result) and else statements?

madth3
  • 7,275
  • 12
  • 50
  • 74
Oualid
  • 403
  • 1
  • 7
  • 22
  • `if (result) document.location.href = this.attr('href');`. No `else` required. – Julian H. Lam Jun 07 '13 at 15:06
  • When I used this.attr('href'); I get TypeError: this.attr is not a function. When I change to $(this).attr('href'); i get Undefined. Any idea? – Oualid Jun 07 '13 at 21:09
  • Hm... what if you just tried `this.href`? – Julian H. Lam Jun 11 '13 at 16:12
  • 1
    I think the issue with @JulianH.Lam's solution is a scope issue. $(this) as the link doesn't exist in the bootbox.confirm() function. I've had a similar issue. My solution was to create a hidden button and a visible button and then in the if(result) { } call $("#hiddenbuttonID).click(). – RandomWebGuy Jun 18 '13 at 17:25
  • I found how to solve the problem and you can find answer here: http://stackoverflow.com/questions/11379794/jquery-click-event-preventdefault/18805115#18805115 – lonecat Sep 14 '13 at 18:38

2 Answers2

19

This worked for me. Grab the "click" href and use it when you have "result".

  <script>
        $(document).on("click", ".alert", function(e) {
            var link = $(this).attr("href"); // "get" the intended link in a var
            e.preventDefault();    
            bootbox.confirm("Are you sure?", function(result) {    
                if (result) {
                    document.location.href = link;  // if result, "set" the document location       
                }    
            });
        });
    </script>
Sylvain Jacob
  • 306
  • 3
  • 4
2

This works great!

$(".alert").on("click", function (e) {
    // Init
    var self = $(this);
    e.preventDefault();

    // Show Message        
    bootbox.confirm("Are you sure?", function (result) {
        if (result) {                
            self.off("click");
            self.click();
        }
    });
});
Community
  • 1
  • 1
Sysem
  • 21
  • 1