jfreak53
jfreak53

Reputation: 2349

Javascript Alertify with return from confirm

I'm trying to use alertify.js as a confirmation dialog for all my confirm scripts. But it just isn't working like regular JS confirm does. In the code below I never get a return true

function aConf ( mes ) {
    alertify.confirm( mes, function (e) {
        return e;
    });
}

<a href="#" onclick="if(aConf(\'Are you sure you wish to remove this?\')) { function(); } return false;">Delete</a>

Of course if I replace aConf with JS' confirm it works. So why is alertify not sending me back it's outcome?

Upvotes: 10

Views: 19793

Answers (2)

Salih ŞEKER
Salih ŞEKER

Reputation: 209

i can solve this problem ,my solution asnyc await function :

Example :

{

function confirmDialogAsync(message = "", okText="Yes", cancelText="No") {
        return new Promise((resolve) => {
            alertify.confirm(
                message, 
                () => {resolve(true);},
                () => {resolve(false);}
            )
            .set({ title: " " })
            .set({ labels: { ok: okText, cancel: cancelText } });
        });
      }

const saveControlValidation = async () => {

console.log(1); 

 if (!(await confirmDialogAsync("Hello Salih ŞEKER","Hi","Bye"))) {
               return false;
    }

console.log(2);

}

}

Upvotes: 0

Levi
Levi

Reputation: 2113

Because confirm is a blocking function (no javascript will run until it returns true/false), and alertify is non-blocking (JS keeps executing). Alertify does not immediately return a true/false, but instead, it probably returns undefined immediately, then it calls a callback function later, after the user clicks OK or Cancel. The return value from that callback function has no effect in your example, because the onclick code has already finished running (because it is non-blocking).

Assuming you are using this: https://github.com/fabien-d/alertify.js/

This is how it actually works with a callback function, not a return value:

alertify.confirm( message, function (e) {
    if (e) {
        //after clicking OK
    } else {
        //after clicking Cancel
    }
});

For your code sample, you might try something like this:

function performDelete ( a_element ) {
    // perform your delete here
    // a_element is the <a> tag that was clicked
}

function confirmAction ( a_element, message, action ) {
    alertify.confirm(message, function(e) {
        if (e) {
            // a_element is the <a> tag that was clicked
            if (action) {
                action(a_element);
            }
        }
    });
}

<a href="#" onclick="confirmAction(this, 'Are you sure you wish to remove this?', performDelete); return false;">Delete</a>

EDIT: updated to be a generic confirm dialog that calls a callback function if the user clicks ok.

Upvotes: 11

Related Questions