Using a function variable in another function

Asked

Viewed 2,141 times

3

I have a variable that has the resulting value of a function, I need to use that same value in another function.

Ex:

el1.on('change', function'){
    //função pra trazer o valor que quero
    var IdResult1 = 123 //valor que a função acima trouxe
    $('.meuLink').attr('href','?parametro1='+idResult1)});



el2.on('keyup', function'){
    //Outra função pra trazer outro valor
    var idResult2 = 456 //valor que a função acima trouxe
    $('.meuLink').attr('href','?parametro1='+idResult1+'&parametro2='+idResult2); // quero usar a variavel aqui
});

1 answer

7


Declare the variable out of functions at a level of scope common to both:

var IdResult1;
el1.on('change', function'){
    //função pra trazer o valor que quero
    IdResult1 = 123 //valor que a função acima trouxe
    $('.meuLink').attr('href','?parametro1='+idResult1)
});

el2.on('keyup', function'){
    //Outra função pra trazer outro valor
    var idResult2 = 456 //valor que a função acima trouxe
    $('.meuLink').attr('href','?parametro1='+idResult1+'&parametro2='+idResult2); // quero usar a variavel aqui
});

For this to work, the keyup of el1 need to occur before the other, or the variable will be without defined value when the keyup of el2.

  • Ball show, it worked but the stranger I had tried before using var idResult1 = ""; didn’t work and leaving so it worked :D Thanks!

  • It must work by assigning an initial value as well, as long as it is outside the function.

Browser other questions tagged

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