Problems with counter

0

I have the following counter:

  • It is inside a table in which foods are selected through a checkbox; So, its function is to calculate the sum of the kcal of the foods that are selected.
  • The problem is that it is used in several sections of the same page and it started with the addition of the previous checkbox. Therefore, I tried to improve it with the properties of the javascript objects, hence caloriasT ['name']. The problem is that it returns 'NaN'. Where this error? Thank you!

    caloriasT={};
    
    function contador(checkbox,kcal,nombre) {
       var sum=parseFloat(kcal);
       if($(checkbox).is(":checked")){
          caloriasT['nombre']+=sum;
       }else{
          caloriasT['nombre']-=sum;
       }
       $("#"+nombre).html(Math.abs(caloriasT['nombre']).toFixed(2)+'       Kcals');
    }
    
asked by Roledi 01.07.2017 в 19:51
source

1 answer

2

The main problem is that you add a value to a variable that still has no defined value (no, the variables are not initialized to 0 , its initial value is undefined ) so you should add:

if (typeof caloriasT[nombre] === 'undefined') {
    caloriasT[nombre] = 0;
}

before adding or subtracting anything. link

Apart from that, you're using the 'nombre' tag instead of the nombre parameter everywhere, but that's an autoforma.

    
answered by 01.07.2017 / 20:18
source