Prevent a link, confirm and then goto location jquery

esafwan picture esafwan · Jul 25, 2011 · Viewed 34k times · Source

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?

Answer

locrizak picture locrizak · Jul 25, 2011

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));

});