Search code examples
jquerypopupconfirmationpreventdefault

Prevent a link, confirm and then goto location jquery


I have links like this.

<a href="delete.php?id=1" class="delete">Delete</a>

If a user click on it. A confirmation should popup and then only if user click yes, it should goto the actual url.

I know that this can prevent the default behavior

    function show_confirm()
    {
    var r=confirm("Are you sure you want to delete?");
    if (r==true)   {  **//what to do here?!!** }

    }    


    $('.delete').click(function(event) {
    event.preventDefault();
    show_confirm()
    });

But how do i continue to that link or send an ajax post to that link after confirming?


Solution

  • you could do it all within the click:

    $('.delete').click(function(event) {
        event.preventDefault();
        var r=confirm("Are you sure you want to delete?");
        if (r==true)   {  
           window.location = $(this).attr('href');
        }
    
    });
    

    Or you could do it by passing the clicked element to the function:

    function show_confirm(obj){
        var r=confirm("Are you sure you want to delete?");
        if (r==true)  
           window.location = obj.attr('href');
    }    
    $('.delete').click(function(event) {
        event.preventDefault();
        show_confirm($(this));
    
    });