How do I add confirm function to links in jQuery so that the dialog always appears?

Rich picture Rich · Jul 20, 2010 · Viewed 9.8k times · Source

I have a HTML table that displays rows of records and has a column on the end with a delete link. Each delete link has a class of confirm-delete. I need to have a confirm dialog popup on click and as it is used in multiple pages, have created a confirm function in an external JS file.

I have added the function call to the link's click using jQuery [code at bottom of post] and it works fine until the dialog has been confirmed once [user has clicked OK]. Then the function is no longer called.

I think I am missing something pretty simple though as I don't use JS/jQuery much I may have a gap in my knowledge. Why does it work fine until the first OK? It appears to be storing a reference to the result and reusing it rather than a unique one for each link.

Here's the code when used on the Notes page:

$(function() {
        // Add Confirmation dialogs for all Deletes
        $("a.confirm-delete").click(function(event) {
            return fConfirmDelete('Note');
        });
});

And the fConfirmDelete function

function fConfirmDelete( deleteObj ) {
    return confirm('Are you sure you wish to delete this ' + deleteObj + '?');
} 

Answer

Kip picture Kip · Jul 20, 2010

After the user clicks OK the first time, do you somehow reload the table dynamically? If so, it could be that the event isn't bound to the re-loaded table. Try a live event handler instead:

jQuery 1.7+

$(function() {
        // Add Confirmation dialogs for all Deletes
        $(document).on('click', 'a.confirm-delete', function(event) {
            return fConfirmDelete('Note');
        });
});

jQuery 1.3-1.8:

$(function() {
        // Add Confirmation dialogs for all Deletes
        $("a.confirm-delete").live('click', function(event) {
            return fConfirmDelete('Note');
        });
});

In your original code, $("a.confirm-delete").click(...) will only bind the event to a.confirm-delete objects already in the DOM. If you add a new a.confirm-delete element later, the event is not bound to it. By using jQuery's live event handler, the event will be bound to any a.confirm-delete elements that currently exist or any that get created dynamically.