Confirm before submitting javascript function

4

When I submit a form, through onsubmit(checkFormIsCorrect()) , I call this javascript function that will validate several situations and submit or not the form.

In this function:

function checkFormIsCorrect() {
    if (!$('div.has-error').length > 0) {
        return displayAlertify('confirm',
                'Confirme todos os dados antes de submeter');
    }
    return false;
}

The displayAlertify(...) function shows a box with the "OK" and "CANCEL" buttons, returning true or false .

The problem is that I can not stop the execution of the code until I get the return of the displayAlertify(...) function.

    
asked by anonymous 29.08.2016 / 16:22

2 answers

3

The function displayAlertify returns nothing.

* Expanded code of comments *

function displayAlertify(message) {

    /* escopo anterior */

    alertify.confirm(message, function(e) {

        /* novo escopo */

        if (e) {
            /* retorna para onde foi chamado */
            return true;
        } else
            /* retorna para onde foi chamado */
            return false;
    });
}

- Callback in alertify.confirm does not execute return in the previous scope. By the way, it would not make sense.

Furthermore, since the onsubmit callback executes, it can not return a value to itself yet, since the execution expires . It is so with all functions. So when the user probably confirms the alert, the onsubmit callback will have expired sooner.

And that's enough, break the form submission until the alertify alert is committed, then resubmit.

function checkFormIsCorrect() {
    if ($('div.has-error').length <= 0) {
        displayAlertify('confirm', 'Confirme todos os dados antes de submeter');
    }
    /* break */
    return false;
}

function displayAlertify(message) {
    alertify.confirm(message, function(e) {
        /* submete o formulário */
        if (e) $('form')[0].submit();
    });
}
    
29.08.2016 / 17:04
1

Problem solved.

It looks like this:

function checkFormIsCorrect() {
    if (!$('div.has-error').length > 0) {
         displayAlertify('confirm',
                 'Confirme todos os dados antes de submeter');
    }
    return false;
}

function displayAlertify(type, message) {
    alertify.confirm(message, function(e) {
        if (e) $('form')[0].submit();
        e.preventDefault();
    });
 }
    
30.08.2016 / 10:45