Adding variables with Javascript

Asked

Viewed 5,078 times

0

I have the following function in Javascript:

function soma(){

var pacote = document.getElementsByName('Pacote');
    for (var i = 0; i < pacote.length; i++){
        if ( pacote[i].checked ) {
            if(pacote[i].value == "Pacote i"){
                var ValorPacoteI = 1000.00;
            }else if (pacote[i].value == "Pacote ii") {
                var ValorPacoteII = 2000.00;
            }else if (pacote[i].value == "Pacote iii") {
                var ValorPacoteIII = 3000.00;
            }
        }
    }
var somar = ValorPacoteI + ValorPacoteII + ValorPacoteIII;
alert(somar.toFixed(2));
}

I need to add up the values of the packages, but when I select the first and the second, Nun appears, only marking the third one that makes the calculation.How would I make the user select any of the packages the calculation is done, without being required to click on all?

  • 2

    You can show the HTML you have?

2 answers

4


You need to declare the variables in your function to have access to msm within the function, as soon as , declaring it within the IF block, you will only have access to this code block, declaring it at the beginning of the sum() function, we have access to msm throughout the function

function soma(){

var ValorPacoteI = 0;
var ValorPacote2 = 0;
var ValorPacote3 = 0;

var pacote = document.getElementsByName('Pacote');
    for (var i = 0; i < pacote.length; i++){
        if ( pacote[i].checked ) {
            if(pacote[i].value == "Pacote i"){
                ValorPacoteI = 1000.00;
            }else if (pacote[i].value == "Pacote ii") {
                ValorPacoteII = 2000.00;
            }else if (pacote[i].value == "Pacote iii") {
                ValorPacoteIII = 3000.00;
            }
        }
    }
var somar = ValorPacoteI + ValorPacoteII + ValorPacoteIII;
alert(somar.toFixed(2));
}
  • add the explanation of the change will improve your response

  • Perfect Renan. It worked! Thanks again.

  • I forgot to explain, sorry @Sanction.

  • 1

    @Jose.Marcos , it worked ? can mark the answer as solved ? and for nothing, anything I am available.

  • It gave yes Renan. I tried to score at that time, but I had to wait a few minutes to make the rs. I marked as solved ;)

  • There is a misconception in your reply @Renandegrandi. Relating to the declaration of variables in Javascript.

Show 1 more comment

2

I’ll copy Renan Degrandi’s answer just to correct a concept flaw about Javascript.

Consider the following code:

function soma(){

var pacote = document.getElementsByName('Pacote');
    for (var i = 0; i < pacote.length; i++){
        if ( pacote[i].checked ) {
            if(pacote[i].value == "Pacote i"){
                var ValorPacoteI = 1000.00;
            }else if (pacote[i].value == "Pacote ii") {
                var ValorPacoteII = 2000.00;
            }else if (pacote[i].value == "Pacote iii") {
                var ValorPacoteIII = 3000.00;
            }
        }
    }
var somar = ValorPacoteI + ValorPacoteII + ValorPacoteIII;
alert(somar.toFixed(2));
}

Although the problem is caused by the declaration of variables within the IF, why this cause problem is wrong. In Javascript there is no block scope. There are only function scope or global scope. Therefore, declaring the variable within the IF is the same as:

function soma(){
//As declarações de variáveis são movidas para o topo do escopo, neste caso a função soma.
var ValorPacoteI;
var ValorPacote2;
var ValorPacote3;

var pacote = document.getElementsByName('Pacote');
    for (var i = 0; i < pacote.length; i++){
        if ( pacote[i].checked ) {
            if(pacote[i].value == "Pacote i"){
              // No entanto a atribuição permanece no mesmo lugar do código.
                ValorPacoteI = 1000.00;
            }else if (pacote[i].value == "Pacote ii") {
              // No entanto a atribuição permanece no mesmo lugar do código.
                ValorPacoteII = 2000.00;
            }else if (pacote[i].value == "Pacote iii") {
              // No entanto a atribuição permanece no mesmo lugar do código.
                ValorPacoteIII = 3000.00;
            }
        }
    }
/*Sendo assim, quando apenas um ou dois checkboxes estiverem marcados,
 o valor das variáveis referentes aos que não estiverem marcados serão sempre undefined.
Quando tentamos calcular qualquer número contra um valor undefined 
o resultado é um NaN(Not a Number). */
var somar = ValorPacoteI + ValorPacoteII + ValorPacoteIII;
alert(somar.toFixed(2));
}

When moving the variable declaration to the top of the function, what actually happened was that the initial value of the variables was changed from Undefined to 0(zero). What made the calculation possible.

function soma(){
   var ValorPacoteI = 0;
   var ValorPacote2 = 0;
   var ValorPacote3 = 0;
/*...*/
}

This behavior is called "Hoisting Declaration", or "Hoisting Statement". You can learn more about the subject at this link:

https://developer.mozilla.org/en-US/docs/Glossary/Hoisting

And below the way to solve the problem: (It’s not the way I’d prefer to solve this problem. But it’s closer to your own code).

function soma(){
var somar = 0,
    pacote = document.getElementsByName('Pacote');
    for (var i = 0, len=pacote.length; i < len; i++){
        if ( pacote[i].checked ) {
            if(pacote[i].value == "Pacote i"){
                somar = somar + 1000.00;
            }else if (pacote[i].value == "Pacote ii") {
                somar = somar + 2000.00;
            }else if (pacote[i].value == "Pacote iii") {
                somar = somar + 3000.00;
            }
        }
    }
   alert(somar.toFixed(2));
}

Browser other questions tagged

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