Search code examples
javascriptjquerytwitter-bootstrapbootbox

$(this).attr("href") return undefined


I am trying to use bootbox with Twitter Bootsrap.

In the code below when I use this.attr('href'); and I get TypeError: this.attr is not a function.

When I change to $(this).attr('href'); i get Undefined.

 <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) {
            document.location.href = this.attr('href'); // doesn't work
            document.location.href = $(this).attr('href'); // Undefined
        }               
    });

    });
</script>

Any idea?


Solution

  • That's not your jQuery event callback function anymore, but the bootbox callback... try $.proxy to bind the context:

    $(document).on("click", ".alert", function(e) {
        e.preventDefault();
    
        bootbox.confirm("Are you sure?", $.proxy(function(result) {
            if (result) {
                document.location.href = this.href;
            }
        }, this));
    });