Search code examples
javascriptjquerysweetalertsweetalert2

Sweetalert component is not firing inside a loop with javascript


Within an onclick event, there are three sweetalert's used for validation. I'm working with rows that are added and removed dynamically, using jquery and javascript.

The problem is that the second sweetalert (which is inside the loop) seems to be conflicting with the third sweetalert, as it is not firing ... The curious thing is that the first sweetalert and the third sweetalert are always working and running normally. When I comment on the third sweetalert part, the second sweetalert (which is inside the loop) starts to work. I've tried everything, but it seems that there is something conflicting with the second sweetalert, perhaps, due to the fact that it is inside a loop, or something else ... Does anyone know how to help me?

HTML:

<div class="tab-pane" id="tabPessoaAnaliseCredito" role="tabpanel">
    <div class="form-horizontal">
        <div class="form-group row">
            <div class="col-md-12">
                <div class="col-md-12" id="div-pessoa-analise-credito">
                    <div class="form-group align-items-center row row-pessoa-analise-credito">
                        <div class="card card-shadow col-md-12 pl-0 pr-o pt-0 pb-0 border border-default">
                            <div class="card-block">
                                <div class="nav-tabs-horizontal" data-plugin="tabs">                    
                                    <div class="tab-content pt-20">
                                        <div class="tab-pane active tb-geral-conteudo" id="tb-geral-pessoa-analise-credito[@indiceI]" role="tabpanel">                       
                                            <div class="form-group row">
                                                <div class="col-md-12">
                                                    <div class="col-md-12" id="div-pessoa-analise-credito-consulta">                                   

                                                    
                                                    </div>
                                                </div>
                                            </div>
                                        </div>                    
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="form-group row">
        <div class="col-md-2">
            <button type="button" id="btn-add-pessoa-analise-credito" class="btn btn-dark">
                <i class="icon wb-plus" aria-hidden="true"></i>
                Nova Análise de Crédito
            </button>
        </div>
    </div>
</div>

JS:

$("#div-pessoa-analise-credito").on("click", ".btn-encerrar-pessoa-analise-credito", function (e) {
    e.preventDefault();

    var indiceI = $(this).closest('.row-pessoa-analise-credito').index();
    var hidPessoaAnaliseCreditoAnaliseEncerrada = $(this).closest('.row-pessoa-analise-credito').find('.hid-pessoa-analise-credito-analise-encerrada');
    var rowPessoaAnaliseCredito = $(this).closest('.row-pessoa-analise-credito');
    
    //Primeiro sweetalert 
    if (hidPessoaAnaliseCreditoAnaliseEncerrada.val() === 'True') {
        swal("Atenção!", "Análise de Crédito já [Encerrada]. :|", "warning");

        return false;
    }      
    
    //Segundo sweetalert 
    $(rowPessoaAnaliseCredito).find('.row-pessoa-analise-credito-consulta').each(function (indiceJ, elemento) {

        var orgaoProtecaoCredito = $(elemento).find('.sel-pessoa-analise-credito-consulta-orgao-protecao-credito').val();
        if (orgaoProtecaoCredito === '') {

             swal("Oops!", "O campo [Órgão de Proteção ao Crédito] é obrigatório.", "error");

            return false;
           
        }
    });
    
    //Terceiro sweetalert 
    swal({
        title: "Tem certeza?",
        text: "Esta operação encerrará e bloqueará permanentemente esta Análise de Crédito.",
        type: "warning",
        showCancelButton: true,
        confirmButtonClass: "btn-warning",
        confirmButtonText: 'Sim, prosseguir!',
        cancelButtonText: "Não, cancelar!",
        closeOnConfirm: false,
        closeOnCancel: false
        //timer: 2000
    }, function (isConfirm) {
        if (isConfirm) {
            hidPessoaAnaliseCreditoAnaliseEncerrada.val('True');
            bloquear_campos_pessoa_analise_credito(indiceI, rowPessoaAnaliseCredito);

            $(rowPessoaAnaliseCredito).find('.row-pessoa-analise-credito-consulta').each(function (indiceJ, elementoPessoaAnaliseCreditoConsulta) {
                bloquear_campos_pessoa_analise_credito_consulta(indiceI, indiceJ, elementoPessoaAnaliseCreditoConsulta);
            });

            swal("Sucesso!", "A Análise de Crédito foi encerrada e bloqueada! :)", "success");

        } else {
            swal("Cancelado", "Operação cancelada! :)", "error");
        }

        
    });

    //remove eventos (Atenção: se remover a limpeza dos dois eventos, a tabulação não funcionará, pois o Alert joga o foco todo para ele.)
    window.onkeydown = null;
    window.onfocus = null;
});

Solution

  • The return false; statement inside the .each(function (indiceJ, elemento) {..}); just breaks out of the loop but does not prevent execution from continuing on to the //Terceiro sweetalert logic within the overall click event function.

    I suspect that adding a flag to check after the .each() loop to determine if you should continue or not is what you need:

    // ...
    //Segundo sweetalert 
    var validationFailed = false;  // define our flag
    $(rowPessoaAnaliseCredito).find('.row-pessoa-analise-credito-consulta').each(function (indiceJ, elemento) {
    
        var orgaoProtecaoCredito = $(elemento).find('.sel-pessoa-analise-credito-consulta-orgao-protecao-credito').val();
        if (orgaoProtecaoCredito === '') {
    
             swal("Oops!", "O campo [Órgão de Proteção ao Crédito] é obrigatório.", "error");
            validationFailed = true; // set the flag
            return false;
           
        }
    });
    
    // check our flag
    if(validationFailed){
       return false; 
    }
    
    //Terceiro sweetalert 
    // ...