Stop running a javascript function, inside jQuery each?

Asked

Viewed 865 times

0

I need to interrupt the execution of .each when an option is not met, I am using return false;, but the code after the block each is still running. Follow the example of the code:

function Salvar(element){
      //$(element).parent().parent().children("td:nth-child(1)").css({"color": "red", "border": "2px solid red"});
      var par = $(element).parent().parent();
      var date = par.children("td:nth-child(1)").children().val();
      par.children().each(function(i){
          if(par.children("td:nth-child("+i+")").children().val() == ''){
            par.children("td:nth-child("+i+")").children().addClass('error').focus();
            return false;
          }else{
            $('#tbl-metas tbody tr td input').removeClass('error');
          }
      });
        
        var data      =   par.children("td:nth-child(1)").children().val();
        var va     =   par.children("td:nth-child(2)").children().val();
        var vb  =   par.children("td:nth-child(3)").children().val();
        var vc       =   par.children("td:nth-child(4)").children().val();

        console.log('data: '+data+' va: '+va+' vb: '+vb+' vc: '+vc);
  }
.error{
  color: red; 
  border: 2px solid red;
  }
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table" id="tbl-metas">
        <caption>Cadastro de metas</caption>
            <thead>
                <tr>
                    <th>Mês</th>
                    <th>Venda 1</th>
                    <th>Venda 2</th>
                    <th>Venda 3</th>
                    <th>Ajuste</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td><input type="date" name="month" value="<?= date('Y-m').'-01' ?>"  style="width:100%"></td>
                    <td><input type="text" class="money" name="txtVendaA" id="txtVendaA" style="width:100%"></td>
                    <td><input type="text" class="money" name="txtVendaB" id="txtVendaB" style="width:100%"></td>
                    <td><input type="text" class="money" name="txtVendaC" id="txtVendaC" style="width:100%"></td>
                    <td><button class="btn btn-success btn-sm" id="btnSave" name="btnSave" onclick="Salvar(this)">Salvar</button></td>
                </tr>
            </tbody>
        </table>

  • 3

    And why don’t you make one for normal which is much simpler?

  • 1

    And performatic. :)

2 answers

1


As suggested in the comments by Maniero, the most ideal is you use the loop for. Something more or less like this:

function getEl() {
  var $els = $('ul > li');
  
  for (var i = 0; i < $els.length; i++) {
    var text = $($els[i]).text();
    
    if (text === '2') {
      // O valor a seguir será retornado pela função "getEl":
      return text
    }
  }
}

console.log(getEl());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
</ul>

However, if you really want to use the jQuery.each (do not recommend), you can do something like this:

function getEl() {
  var $els = $('ul > li');
  
  // Crie um valor logo antes de iniciar as iterações:
  var returnValue = undefined;
  
  $els.each(function() {
    var text = $(this).text();
    
    if (text === '2') {
      // Atribuímos o valor que queremos que a função retorne à variável "returnValue" e, em seguida, interrompemos o loop:
      returnValue = text;
      return false;
    }
  });
  
  // Verifique se o valor de "returnValue" foi alterado. Se sim, retorne o valor.
  if (typeof returnValue !== 'undefined') {
    return returnValue
  }
}

console.log(getEl());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
</ul>


In short, the two solutions are valid. But, to confess, the use of jQuery.each or .each is extremely unnecessary, since Javascript alone already has several ways to create loops. Some examples are:

  • Solved using for, it is a problem for jquery to continue execution even using return false;? I will continue looking to understand the operation, thank you very much.

0

function Salvar(element){
      //$(element).parent().parent().children("td:nth-child(1)").css({"color": "red", "border": "2px solid red"});
      var par = $(element).parent().parent();
      var date = par.children("td:nth-child(1)").children().val();
      par.children().each(function(i){
          if(par.children("td:nth-child("+i+")").children().val() == ''){
            par.children("td:nth-child("+i+")").children().css({"color": "red", "border": "2px solid red"}).focus();
            break;
          }            
      });
        var data      =   par.children("td:nth-child(1)").children().val();
        var va     =   par.children("td:nth-child(2)").children().val();
        var vb  =   par.children("td:nth-child(3)").children().val();
        var vc       =   par.children("td:nth-child(4)").children().val();

        console.log('data: '+data+' va: '+va+' vb: '+vb+' vc: '+vc);
  }

Try to replace the false Return by break according to the above code.

  • I’ve done it, stay the same, thank you.

Browser other questions tagged

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