How to use a Global variable in two Jquery codes to execute conditions?

0

Here's a simplified example of what I'm doing. I need to check if the variables passed before and that would change the Global are true in the checkbox.

$(document).ready(function() {

  var usuario_ok;

  $('#cadastro').on('keyup', 'input', function() {
    var c_nome = $('#c_nome').val();
    // Verificar Nome

    if (c_nome.length > 2) {
      var usuario_ok = true;
    } else {
      var usuario_ok = false;
    }
    //alert(usuario_ok);

  });

  $('#cadastro').on('change', '#c_concordo', function() {
    var c_chk = this.checked ? true : false;

    if (c_chk == true && usuario_ok == true) {
      $('#deu_certo').html('OK');
    }
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><formid="cadastro">
  <input type="text" id="c_nome" />
  <input type="checkbox" id="c_concordo">
</form>
<div id="deu_certo">Ainda não</div>
    
asked by anonymous 13.07.2017 / 20:21

3 answers

2

In Javascript, a variable is global if it is declared without var , or declared in global scope.

This is local:

function () {
    var foo = 1;
}

This is always global:

bar = 1;

This is also global, but if you are in global scope:

var ni = 1;

Now these three forms can lead to the invocation of cosmic horrors, especially when your code grows and you have to maintain it. Is there a more readable and less error-prone way to have a variable accessible at any point in the code:

window.usuarioOk = true;

If you want to have multiple global variables like this, it is best to declare them as properties of an object. So:

window.minhasGlobais = {
    usuarioOk: true,
    foo: 1,
    bar: 2,
    palmeirasTemMundial: false
    /*etc.*/
}

So these variables can be accessed from anywhere, and in an unambiguous way for anyone reading the code.

    
13.07.2017 / 20:28
1

In JavaScript each function determines a new scope of variables. And functions declared within other functions see external variables - unless they redeclarate variables with the same name locally. For example, in a code with the same structure as yours:

function externa() {

    var valor = 'externa';


    function primeiraInterna() {
        var valor = 'primeira interna'; // não afeta o valor de fora, e também
                                        // impede acesso ao valor de fora
    }

    function segundaInterna() {
        console.log(valor);             //  tem acesso ao valor de fora
        valor = 'segunda interna';      //  afeta o valor de fora
    }

}

Therefore, in your keyup treatment do not use var when referring to usuario_ok , otherwise you create a local variable and lose access to the outer one (which in your example is not exactly global).

    
13.07.2017 / 20:48
0

And only remove% with% of variable% with% in this part:

if (c_nome.length > 2) {
    var usuario_ok = true;
} else {
    var usuario_ok = false;
}

If you use var you will be re-declaring the variable var so it did not work.

Change your code to:

if (c_nome.length > 2) {
    usuario_ok = true;
} else {
    usuario_ok = false;
}

Code working:

$(document).ready(function() {

  var usuario_ok;

  $('#cadastro').on('keyup', 'input', function() {
    var c_nome = $('#c_nome').val();
    // Verificar Nome

    if (c_nome.length > 2) {
      usuario_ok = true;
    } else {
      usuario_ok = false;
    }
    //alert(usuario_ok);

  });

  $('#cadastro').on('change', '#c_concordo', function() {
    var c_chk = this.checked ? true : false;

    if (c_chk == true && usuario_ok == true) {
      $('#deu_certo').html('OK');
    }
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><formid="cadastro">
  <input type="text" id="c_nome" />
  <input type="checkbox" id="c_concordo">
</form>
<div id="deu_certo">Ainda não</div>
    
13.07.2017 / 20:52