Declare a global variable in Jquery

0

How can I declare a Jquery variable globally?

I have searched for a way to declare a variable globally, in which I can access the value of a <input> since the problem is in which the variable is used in at least 20 other functions. I usually declare the functions in the following way:

function Funcion1(){
    var valor1 = $('#objeto1').val();
    var valor2 = $('#objeto2').val();
    var valor3 = $('#objeto3').val();

    Generar(valor1,valor2,valor3);
}

/*
* mismos objetos utilizados que en Funcion1
*/
function Funcion2(){
    var valor0 = "objeto";
    var valor1 = $('#objeto1').val();
    var valor2 = $('#objeto2').val();
    var valor3 = $('#objeto3').val();

    Otro(valor0,valor1,valor2,valor3);
}

... (n funciones)

What is the correct way to declare globally a var dato = $('#dato').val(); ?

Here is an example of what my idea is like:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  Tu nombre:<br>
  <input id="dato" type="text">
  <button id="boton">ok</button>
<script>
    var saludo = 'Hola ';
    var dato = $('#dato').val();  //¿Cuál es la mejor manera?
    
    $('#boton').click(function(){
      alert(saludo + '\r\n' + dato); //no obtiene el dato de manera global
    });
</script>
    
asked by iuninefrendor 18.01.2018 в 05:51
source

1 answer

2

The code you have for testing is fine, but at no time do you tell the variable that you should take the value you enter in the input each time you change it. So I leave you this example and I hope it serves you:

$(document).ready(function() {
    var saludo = 'Hola ';
    var dato;
    $("#dato").on("blur", function(){
    dato = $(this).val();
    });
    $('#boton').click(function(){
      alert(saludo + ' ' + dato);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  Tu nombre:<br>
  <input id="dato" type="text">
  <button id="boton">ok</button>

What the function .blur() does is detect the moment when an element is out of focus, in this case when writing in the input and then the button is pressed, when pressing the button the focus of the input is lost and activate the function.

    
answered by 18.01.2018 / 06:28
source