Add variables with Javascript

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 the values of the packages, but when I select the first and second, NuN appears, only marking the third one that does the calculation. How would I make the user to select any of the packages the calculation is done, without Is it compulsory to click on all of them?

    
asked by anonymous 31.08.2015 / 15:38

2 answers

4

You need to declare the variables in your function to access msm within the function, as soon as you declare it inside the IF block, you will only get access to that block of code, declaring it at the beginning of the soma () 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));
}
    
31.08.2015 / 15:41
2

I'm going to copy Renan Degrandi's answer just to correct a concept glitch over 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 the 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));
}

By moving the declaration of variables 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 "Declaration Hoisting". You can learn more about this at this link:

link

And below is how to solve the problem: (It is not the way I would prefer to solve this problem, but it is 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));
}
    
03.11.2015 / 17:34