How to use a variable declared within a function, in another function?

Asked

Viewed 122 times

-4

I want to use the Cpf variable in another function!!

function enviar(){

    var nome = document.getElementById('input_Nome').value
    var cpf= document.getElementById('input_Cpf').value
    var  data_de_nascimento = document.getElementById('input_DataDeNascimento').value
    var  endereço = document.getElementById('input_Endereço').value
    var res = document.getElementById('res')
    var fsex = document.getElementsByName('radsex') 
    var fdeficiencia = document.getElementsByName('rad_deficiencia')
    var genero = ''
    var deficiencia = ''

        if (fsex[0].checked){
            genero = 'Homem'
        }else if (fsex[1].checked){
            genero= 'Mulher'
        }

        if(fdeficiencia[0].checked){
            deficiencia = 'Sim'
        }else if(fdeficiencia[1].checked){
            deficiencia= 'Não'
        }       

        
}

  • Declare out of it...

  • Hello and welcome to Stackoverflow, before you ask questions please take a look at this link how not to ask questions, this will help you to have a higher acceptance rate in your question.

1 answer

2


The variable declared with var within a function will only have scope within that function. As it is explicit that you want to assign a value to the variable cpf when calling the function where it is, it makes no sense to try to reuse the value of this variable in another function, unless you declared the variable with global scope:

var cpf;
function enviar(){
   cpf= document.getElementById('input_Cpf').value
}

Even so the variable cpf would only have some value if the function enviar() was called before the other function.

But since it’s good to avoid global variables, it doesn’t make much sense to do that. Just use another variable by taking the same value as cpf handle inside function enviar():

function enviar(){
   var cpf= document.getElementById('input_Cpf').value
}

function outraFuncao(){
   var cpf= document.getElementById('input_Cpf').value
}

The values of cpf in both functions will be the same and updated according to the value that is in the element #input_Cpf.

  • Then I put one more trigger on my button to fire the other function?

  • There is no button on the question.

Browser other questions tagged

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