Call function js within another and depending on the result stop the execution of the parent function

Asked

Viewed 171 times

1

Well, I have a function(1) with validations in js, I would like to call it within another function(2) js and if and function one has a result, I would like to stop the execution of function 2 For example:

function validarCamposSimulador() {
if (form_alterar.opcoes.value == "Selecione...") {
    alert("Selecione um Tipo de Empréstimo!");  
    form_alterar.opcoes.focus();
    return false;
}
if (form_alterar.salario_bruto.value == "0,00" || form_alterar.salario_bruto.value == "") {
    alert("Digite seu Salário Bruto");  
    form_alterar.salario_bruto.focus();
    return false;
}
if (form_alterar.desconto.value == "") {
    alert("Digite um Desconto");    
    form_alterar.desconto.focus();
    return false;
}
if (form_alterar.salario_liquido.value == "0,00" || form_alterar.salario_liquido.value == "") {
    alert("Digite seu Salário Liquido");    
    form_alterar.salario_liquido.focus();
    return false;
}
if (form_alterar.valor_sol.value == "0,00" || form_alterar.valor_sol.value == "") {
    alert("Digite o Valor a ser Solicitado");   
    form_alterar.valor_sol.focus();
    return false;
}
}

Now within that function I would like to call the previous

$("#btn_emp").click(function(){
        var valor_maximo = $("#val_max").val();
        var valor_sol = $("#valor_sol").val();
        var valor_entrada = $("#valor_entrada").val();
        var data_inicio = $("#data_inicio").val();
        var prazo = $("#prazo").val();
        data_inicio = data_inicio.replace("/", "-");
        data_inicio = data_inicio.replace("/", "-");
        var auxiliar;
        $.ajax({
          method: "GET",
          url: "../calcularEmprestimo.asp",
          data: { v_sol: valor_sol, v_ent: valor_entrada, prz: prazo,  val_max: valor_max, dt_ini: data_inicio },
          success: function(response) {
           document.getElementById("parcela_inicial").value = response; 
          }
        });
  • I added an answer too. I saw your Dit but I couldn’t figure out which function to call which... you want to call validarCamposSimulador inside the callback of the click and stop if it doesn’t work, that’s it?

  • Thiago, did any of the answers below solve your problem? If yes you can click to mark as accepted. If it does not say, to explain better.

2 answers

2

For this the function exemplo has to return something to be analyzed.

There are two models, synchronous and asynchronous.

Synchronous:

function soNumeros(dados) {
  if (String(dados).match(/^\d+$/)) return true;
  else return false;
}

function exe(algo) {
  var numeroValido = soNumeros(algo);
  if (numeroValido) {
    console.log('Sim!', algo, 'é numero');
  } else {
    console.log('Não!', algo, 'não é numero');
  }
}

[1, 2, 'texto', '3'].forEach(function(teste) {
  exe(teste);
});

Asynchronous

Here you can do with callbacks, or Promises:

Callback:

function soNumeros(dados, done) {
  setTimeout(function() {
    if (String(dados).match(/^\d+$/)) done(true);
    else done(false);
  }, Math.random() * 2000);
}

function exe(algo) {
  soNumeros(algo, function(numeroValido) {
    if (numeroValido) {
      console.log('Sim!', algo, 'é numero');
    } else {
      console.log('Não!', algo, 'não é numero');
    }
  });
}

[1, 2, 'texto', '3'].forEach(function(teste) {
  exe(teste);
});

Promises:

function soNumeros(dados, done) {
  return new Promise(function(passa, falha) {
    setTimeout(function() {
      if (String(dados).match(/^\d+$/)) passa();
      else falha();
    }, Math.random() * 2000);
  });

}

function exe(algo) {
  soNumeros(algo).then(function() {
    console.log('Sim!', algo, 'é numero');
  }).catch(function() {
    console.log('Não!', algo, 'não é numero');
  });
}

[1, 2, 'texto', '3'].forEach(function(teste) {
  exe(teste);
});

  • Thank you, it was not the solution I used (I used the answer below), but showed me how to make other parts of my code, Hugs

1


$("#btn_emp").click(function(){
  if (!validarCamposSimulador()) {
     return false;
  }
  var valor_maximo = $("#val_max").val();
  //...
});

however, for this, you need the function to return TRUE if everything is okay:

function validarCamposSimulador() {
if (form_alterar.opcoes.value == "Selecione...") {
    alert("Selecione um Tipo de Empréstimo!");  
    form_alterar.opcoes.focus();
    return false;
}
if (form_alterar.salario_bruto.value == "0,00" || form_alterar.salario_bruto.value == "") {
    alert("Digite seu Salário Bruto");  
    form_alterar.salario_bruto.focus();
    return false;
}
//..

 return true;//no final de tudo, fora de todos os ifs
}
  • Ola Willian, thank you for your reply. One of the doubts is just how to make the if condition, because it is a js of validations and if it falls into any of his ifs, it returns false. Ah, I’m your fan, always see your answers in forums, helps me a lot at work, thank you double hahaha

  • Hi Thiago! , so your example function needs to return true or false. Function example { if( some problem) { Return true; } Return false } If you want to talk more concretely about what the problem is, I think it will be easier to help you.

  • I’ll edit the question with my code

  • edited my answer.

  • Thank you very much, and congratulations on the book of Ode, it was great

Browser other questions tagged

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