Why is the sum returning 0 and only works when I place the variables as local?

Asked

Viewed 60 times

0

when I place var n1,N2 and s inside the sum Function, only then the result turns out right! because? I’m a beginner.

/*variaveis dos elelentos html*/
var dr1= document.querySelector('input#txtn1')
var dr2= document.querySelector('input#txtn2')
var botao = document.querySelector('button.so')
var r = document.querySelector('div.res')

/*recebe os valores digitados no input*/
var n1= Number(dr1.value)
var n2 = Number(dr2.value)
/*realizar a soma dos valores do input*/
var s = n1 + n2
/*cria um evento para ser chamado*/
botao.addEventListener("click",somar)

function somar(){

    r.innerHTML = s
    r.style.color = 'red'
}
  • 1

    Of the commentary /*recebe os valores digitados no input*/ until the comment /*cria um evento para ser chamado*/ move to first line of function soma().

  • 3

    It is simple, when you execute the code you store the values of the variables, and if you change they are not updated. If you want to get the updated values you have to put the code in the sum function as @Augustovasques commented. Do a debug and you’ll find it easy ;)

  • Vlw, so it is recommended to put the conversion and operation variables within the function as local variables? and when I should or should not use as a global variable would have an example or some bibliography reference about it?

  • "it is recommended to place the conversion and operation variables within the function as local variables" is not about being recommended, only that it needs to be local pq needs to take the updated value, but a broader idea is always to use the local variable, the global is the exception, only use if really need

  • The vlw, I really thank you, hug.

1 answer

2

You are running the sum even before the event is triggered, the sum is running when the page loads, and at this point the inputs are probably empty

When you click the sum ALREADY EXECUTED, then just move everything into the function:

/*variaveis dos elelentos html*/
var dr1= document.querySelector('input#txtn1')
var dr2= document.querySelector('input#txtn2')
var botao = document.querySelector('button.so')
var r = document.querySelector('div.res')

botao.addEventListener("click",somar)

function somar(){

    /*recebe os valores digitados no input*/
    var n1= Number(dr1.value)
    var n2 = Number(dr2.value)
    /*realizar a soma dos valores do input*/
    var s = n1 + n2
    /*cria um evento para ser chamado*/

    r.innerHTML = s
    r.style.color = 'red'
}
<input id="txtn1"> + <input id="txtn2"> = <div class="res"></div>
<button type="button" class="so">Somar</button>

Browser other questions tagged

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