According to the documentation:
You can stop the loop from Within the callback Function by returning false
.
That is, it is sufficient that the function of callback return false
.
Below is a comparison of your code (adapted because HTML was not provided), and the difference when the return is false
:
// imprime "abc" e "def"
console.log('each percorre todos');
$('#analise-credito').find('.row-pessoa-analise-credito-consulta').each(function (indiceJ, elemento) {
var valor = $(elemento).find('.sel-pessoa-analise-credito-consulta-orgao-protecao-credito').val();
if (valor === '') {
return; // <-- esse return não interrompe o each
} else {
console.log(`achei: ${valor}`);
}
});
// imprime somente "abc"
console.log('--------\neach para no primeiro vazio que encontrar');
$('#analise-credito').find('.row-pessoa-analise-credito-consulta').each(function (indiceJ, elemento) {
var valor = $(elemento).find('.sel-pessoa-analise-credito-consulta-orgao-protecao-credito').val();
if (valor === '') {
return false; // <-- retorna false para interromper o each
} else {
console.log(`achei: ${valor}`);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="analise-credito">
<p class="row-pessoa-analise-credito-consulta">
<input type="text" class="sel-pessoa-analise-credito-consulta-orgao-protecao-credito" value="abc">
</p>
<p class="row-pessoa-analise-credito-consulta">
<input type="text" class="sel-pessoa-analise-credito-consulta-orgao-protecao-credito" value=""> </p>
<p class="row-pessoa-analise-credito-consulta">
<input type="text" class="sel-pessoa-analise-credito-consulta-orgao-protecao-credito" value="def"> </p>
</div>
That is, in the first case it goes through all the elements (printing all non-empty ones - in this case, "abc" and "def"). And in the second case, it interrupts when the first blank is found, so just print the "abc".
The option with for
is without jQuery, just use querySelectorAll
and querySelector
to search for the elements you need:
for (const elemento of document.querySelectorAll('.row-pessoa-analise-credito-consulta')) {
var valor = elemento.querySelector('.sel-pessoa-analise-credito-consulta-orgao-protecao-credito').value;
if (valor === '') {
break; // interrompe o for
} else {
console.log(`achei: ${valor}`);
}
}
<div id="analise-credito">
<p class="row-pessoa-analise-credito-consulta">
<input type="text" class="sel-pessoa-analise-credito-consulta-orgao-protecao-credito" value="abc">
</p>
<p class="row-pessoa-analise-credito-consulta">
<input type="text" class="sel-pessoa-analise-credito-consulta-orgao-protecao-credito" value=""> </p>
<p class="row-pessoa-analise-credito-consulta">
<input type="text" class="sel-pessoa-analise-credito-consulta-orgao-protecao-credito" value="def"> </p>
</div>
Thank you @hkotsubo!!!! The problem was to return with "Return". When returning with "Return false", it worked well. :)
– Master JR