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

Asked

Viewed 1,664 times

0

It follows a simplified example of what I am doing. I need to check if the variables passed before and that would modify 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>
<form id="cadastro">
  <input type="text" id="c_nome" />
  <input type="checkbox" id="c_concordo">
</form>
<div id="deu_certo">Ainda não</div>

  • 3

    You are re-declaring the variable with var usuario_ok. You shouldn’t have var there.

3 answers

2

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

That’s local:

function () {
    var foo = 1;
}

This is always global:

bar = 1;

This is also global, but if you are in the 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. There is a more readable and less error-prone way for you 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 a specific way for those reading the code.

1

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

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 treatment of keyup don’t use var when referring to usuario_ok, otherwise you create a local variable and lose access to the most external (which in your example is not exactly global).

0

And just remove the var of the variable usuario_ok in that 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 usuario_ok so it didn’t 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>
<form id="cadastro">
  <input type="text" id="c_nome" />
  <input type="checkbox" id="c_concordo">
</form>
<div id="deu_certo">Ainda não</div>

Browser other questions tagged

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