stop a foreach Java

Asked

Viewed 1,469 times

-1

I have a script that reads each field of the form:

// JavaScript Document
$(document).ready(function (e) {

    $("#cadastrar").on("click", function () {

        $(".required").each(function (i) {
            if ($(this).val() == "") {
                idCampo = $(this).attr("id");
                nomeCampo = idCampo.substr(0, 1).toUpperCase() + idCampo.substr(1);
                alert("Preecha campo " + nomeCampo + ", campo obrigatório");
                $(this).focus();
                return false;
            };
        });
    });

And I have a date field in the form:

<input type="date" max="<?php echo date('Y-m-d'); ?>" class="inputTextMedio required" name="nascimento" id="nascimento" required/>

I’m having 2 problems here.

In the loop foreach, when it arrives in the false Return it up to.

But even so it seems that it continues because I have below a ajax which can only be called if the validations occur normally. But is passing directly.

        foreach.....

        $.ajax({
            url: "_scripts/_php/_validacoes/cadastrarMembro.php",
            type: "POST",
            dataType: "json",
            data: {   
                 dataCadastro : $("#dataCadastro").val(),
                 nome : $("#nome").val(),
                 apelido : $("#apelido").val(),
                 nascimento : $("#nascimento").val(),
                 telefone : $("#telefone").val(),
                 celular : $("#celular").val(),
                 bairro : $("#bairro").val(),
                 endereco : $("#endereco").val(),
                 email : $("#email").val(),
                 sexo : $("#sexo").val(),
                 estadoCivil : $("#estadoCivil").val(),
                 dataBatismo : $("#dataBatismo").val(),
                 bloqueado : $("#bloqueado").val(),
                 batizadoFora : $("#batizadoFora").val(),
                 usuario : $("#usuario").val(),
                 senha : $("#senha").val()
            },
            success: function (result) {
                if (result[0] == "Erro")
                    $(".resposta").html(result[1]);
                else
                    $(".resposta").html(result[1]);
            }
        });


    });


});

Where am I going wrong?

complete code:

// JavaScript Document
$(document).ready(function (e) {

    $("#cadastrar").on("click", function () {

        $(".required").each(function (i) {
            if ($(this).val() == "") {
                idCampo = $(this).attr("id");
                nomeCampo = idCampo.substr(0, 1).toUpperCase() + idCampo.substr(1);
                alert("Preecha campo " + nomeCampo + ", campo obrigatório");
                $(this).focus();
                break();
            };
        });

        $.ajax({
            url: "_scripts/_php/_validacoes/cadastrarMembro.php",
            type: "POST",
            dataType: "json",
            data: {   
                 dataCadastro : $("#dataCadastro").val(),
                 nome : $("#nome").val(),
                 apelido : $("#apelido").val(),
                 nascimento : $("#nascimento").val(),
                 telefone : $("#telefone").val(),
                 celular : $("#celular").val(),
                 bairro : $("#bairro").val(),
                 endereco : $("#endereco").val(),
                 email : $("#email").val(),
                 sexo : $("#sexo").val(),
                 estadoCivil : $("#estadoCivil").val(),
                 dataBatismo : $("#dataBatismo").val(),
                 bloqueado : $("#bloqueado").val(),
                 batizadoFora : $("#batizadoFora").val(),
                 usuario : $("#usuario").val(),
                 senha : $("#senha").val()
            },
            success: function (result) {
                if (result[0] == "Erro")
                    $(".resposta").html(result[1]);
                else
                    $(".resposta").html(result[1]);
            }
        });


    });


});

I also tried the way below and nothing.

requeridos = $(".required");
eachConta = requeridos.length;
alert(eachConta);

for (i=0; i< eachConta; i++) {
    if (requeridos[i].val() == "") {
        idCampo = requeridos[i].attr("id");
        nomeCampo = idCampo.substr(0, 1).toUpperCase() + idCampo.substr(1);
        alert("Preecha campo " + nomeCampo + ", campo obrigatório");
        requeridos[i].focus();
        return false;
    };

}

1 answer

3


The return false will take effect on the function of .each (because it is inside it), not the click function. That is, the loop will be aborted when the if is satisfied, but the rest of the code will be processed normally.

What you can do is create a variable initially true and when the if is met, change to false and put Ajax inside another if by checking whether the variable continues true:

$(document).ready(function (e) {

    $("#cadastrar").on("click", function () {

         var valida = true;

         $(".required").each(function (i) {
            if ($(this).val() == "") {
                idCampo = $(this).attr("id");
                nomeCampo = idCampo.substr(0, 1).toUpperCase() + idCampo.substr(1);
                alert("Preecha campo " + nomeCampo + ", campo obrigatório");
                $(this).focus();
                valida = false;
                return false;
            };
        });        

        if(valida){

            // código do Ajax
        }

    });
});

With for would work with the return false, because it would not have a second function. Only in its for of the question, has two errors: requeridos[i].val() and requeridos[i].attr("id"). The methods .val() and .attr() require jQuery objects. The correct would be:

var requeridos = $(".required");
eachConta = requeridos.length;

for (i=0; i< eachConta; i++) {
    if ($(requeridos[i]).val() == "") {
        idCampo = $(requeridos[i]).attr("id");
        nomeCampo = idCampo.substr(0, 1).toUpperCase() + idCampo.substr(1);
        alert("Preecha campo " + nomeCampo + ", campo obrigatório");
        requeridos[i].focus();
        return false;
    };

}

// código do Ajax
  • shame. kkk. Thank you! tiredness does things

  • but, and the problem of the date field?

  • What would be the problem with the countryside?

  • then, the field is this <input type="date" max="<? php echo date('Y-m-d'); ? >" class="inputTextMedio" name="dataBatismo" id="dataBatismo"/>. If I choose a date all right. But if I do not choose from the error in mysql query and mysql the field accepts empty or null

  • in jquery ajax, before sending to php, I did so $_POST["dataBatismo"] == ""? 'NULL' : $_POST["dataBatismo"] ,, since the field accepts null value

  • Try to use empty($_POST["dataBatismo"]) ? 'NULL' : $_POST["dataBatismo"]

  • same thing. We used to open the imspector of browsers and we could see the return of php to ajax. Now sometimes even the right javascript are displaying on the ispector

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.