Summarizing Selected Columns

2

I have the following scenario:

A table created in the razor with several columns, where each row has a checkbox in place different from each other, and would like to do the checkbox sum clicked by column via javascript, but I have no idea where to start. Could someone help?

<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
    border: 1px solid black;
    border-collapse: collapse;
}
th, td {
    padding: 5px;
    text-align: left;    
}
</style>
</head>
<body>

<h2>Cell that spans two columns:</h2>

<table style="width:100%">
  <tr>
    <th>TESTES</th>
    <th colspan="8">PROBLEMAS</th>
    
  </tr>
  <tr>
    <td></td>
    <td>PROB 1</td>
    <td>PROB 2</td>
    <td>PROB 3</td>
    <td>PROB 4</td>
    <td>PROB 5</td>
    <td>PROB 6</td>
    
  </tr>
  <tr>
    <td>TESTE 1</td>
    <td><input type="checkbox" name="ch[]" value="1" /></td>
    <td><input type="checkbox" name="ch[]" value="1" /></td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
  </tr>
  <tr>
    <td>TESTE 2</td>    
    <td><input type="checkbox" name="ch[]" value="1" /></td>
    <td><input type="checkbox" name="ch[]" value="1" /></td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
  </tr>
  <tr>
    <td>TESTE 3</td>    
    <td><input type="checkbox" name="ch[]" value="1" /></td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
  </tr>
  <tr>
    <td>TESTE 4</td>        
    <td></td>
    <td><input type="checkbox" name="ch[]" value="1" /></td>
    <td></td>
    <td></td>
    <td><input type="checkbox" name="ch[]" value="1" /></td>
    <td><input type="checkbox" name="ch[]" value="1" /></td>
  </tr>
  
  <tr>
    <td>Resultados</td>        
    <td></td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
  </tr>
  
</table>


</body>
</html>
    
asked by anonymous 17.07.2015 / 21:11

1 answer

1

It needs some improvements, but the algorithm may look like this

NOTE: Since column 0 is the description, the value of resultadoCheckboxes[0] will always be 0;

Here has an example (I put it in a TimeOut to give you time to select the checkboxes before it gives a console.log in each value of resultadoCheckboxes )

var linhas = document.querySelectorAll('table tr');
var resultadoCheckboxes = [];
for(var indexLinha = 0, numeroLinhas = linhas.length; 
        indexLinha < numeroLinhas; indexLinha++){
   var colunas = linhas[indexLinha].querySelectorAll('td');
   for(var indexColuna = 0, numeroColunas = colunas.length; 
           indexColuna < numeroColunas; indexColuna++){
       var elemento = colunas[indexColuna].querySelector('input[type=checkbox]')
       if(!resultadoCheckboxes [indexColuna]) resultadoCheckboxes [indexColuna] = 0;
       if(elemento && elemento.checked) {
           resultadoCheckboxes [indexColuna] = resultadoCheckboxes [indexColuna] + 1;
       }
   }
}
    
17.07.2015 / 22:32