How to add variables correctly? [closed]

1

I have a series of checkboxes where the user must select several options and each option increments one or more variables.

// Variáveis das características citopáticas 

var hipercromasia = document.getElementById("hipercromasia");
var cromatina_grosseira = document.getElementById("cromatina_grosseira");
var queratinizacao = document.getElementById("queratinizacao");
var cariomegalia = document.getElementById("cariomegalia");
var binucleacao = document.getElementById("binucleacao");
var coilocito = document.getElementById("coilocito");

// Variáveis que armazenam os checkboxes selecionados

var ASCUS = [];
var ASCH = [];
var LSIL = [];
var HSIL = [];

// Verifica os critérios citológicos

if (hipercromasia.checked) {
  ASCUS++;
  ASCH++;  
} 
if (cromatina_grosseira.checked) {
  HSIL++;
}
if (queratinizacao.checked) {
  LSIL++;
  HSIL++;   
}
if (cariomegalia.checked) {
  HSIL++;
  ASCUS++;  
}
if (binucleacao.checked) {
  HSIL++;
  ASCH++; 
}
 if (coilocito.checked) {
   ASCUS++;
   LSIL++;   
} 

 alert(ASCUS + ASCH + LSIL + HSIL);

The problem occurs when I try to sum the result of the variables to later make the percentage and so on.

For example: If I select "Hyperchromasia" and "Chromatin", it returns me 21, not 3.

How do I sum these variables together?

    
asked by anonymous 02.10.2017 / 05:59

1 answer

3

You should start these counters with 0 and not with [] . There is also a lack of logic to decrease these values if a checkbox is unchecked. If you have a function that runs whenever you need it, this logic can be omitted.

One suggestion would be to do this:

// Variáveis das características citopáticas 
var hipercromasia = document.getElementById("hipercromasia");
var cromatina_grosseira = document.getElementById("cromatina_grosseira");
var queratinizacao = document.getElementById("queratinizacao");
var cariomegalia = document.getElementById("cariomegalia");
var binucleacao = document.getElementById("binucleacao");
var coilocito = document.getElementById("coilocito");

function somar() {
  // Variáveis que armazenam os checkboxes selecionados
  var ASCUS = 0;
  var ASCH = 0;
  var LSIL = 0;
  var HSIL = 0;

  // Verifica os critérios citológicos
  if (hipercromasia.checked) {
    ASCUS++;
    ASCH++;
  }
  if (cromatina_grosseira.checked) {
    HSIL++;
  }
  if (queratinizacao.checked) {
    LSIL++;
    HSIL++;
  }
  if (cariomegalia.checked) {
    HSIL++;
    ASCUS++;
  }
  if (binucleacao.checked) {
    HSIL++;
    ASCH++;
  }
  if (coilocito.checked) {
    ASCUS++;
    LSIL++;
  }
  return ASCUS + ASCH + LSIL + HSIL;
}

var soma = somar();
console.log(soma);
    
02.10.2017 / 07:41