Search code examples
javascriptjquerydialogargumentsconfirm

How to pass button into Jquery function?


I'm using a third party jQuery library called jQquery.confirm. It provides dialogs in jQuery. Upon clicking a button of a particular class I want to use the confirm() function in order to bring up the confirmation:

$(".btn-danger").click(function(event) {
    //Prevent the button from being clicked.
    event.preventDefault();

    $.confirm({
        text: "Are you sure you want to delete that comment?",
        confirm: function() {
            //Code in here for button to be pressed
        }
    });
});

The issue I'm having is with the confirm: function(). I'd like to simply simulate clicking the button here. I've tried this but it doesn't seem to recognize the button that I need to click:

$(this).trigger("click");

I'm guessing I need to pass it as an argument somewhere?


Solution

  • Within the confirm handler function the scope of this will not refer to the button that was clicked. To fix this you need to store a reference to the clicked button in a variable outside of the confirm handler.

    Note however that the logic you're creating will end up in a loop; you're clicking the button, showing the confirm then clicking the button again programmatically which will just show the confirm again and so on ad infinitum. I'd suggest you call a function to do what's needed in the confirm action, like this: Try this:

    $(".btn-danger").click(function(e) {
        e.preventDefault();
    
        $.confirm({
            text: "Are you sure you want to delete that comment?",
            confirm: function() {
                actionWasConfirmed();
            }
        });
    });
    
    var actionWasConfirmed = function() {
        console.log('do something here...');
    };