RustyBadRobot RustyBadRobot - 3 months ago 23
jQuery Question

dataTables alert row/s with most of

I have a simple table with the first column being 'Company' and 5 further Columns for 'Days' which is a Binary '1' or '0'

Using DataTables I am trying to get the Company / Companies names (Column 1) that have the most '1s' for the 5 days:

<table id="table" class="responstable" border="0" cellspacing="0" cellpadding="0">
<thead>
<tr>
<th scope="col">Company</th>
<th scope="col">Day 1</th>
<th scope="col">Day 2</th>
<th scope="col">Day 3</th>
<th scope="col">Day 4</th>
<th scope="col">Day 5</th>
</tr>
</thead>
<tbody>
<tr>
<td>Company1</td>
<td align="center">0</td>
<td align="center">0</td>
<td align="center">1</td>
<td align="center">0</td>
<td align="center">1</td>
</tr>
<tr>
<td>Company2</td>
<td align="center">0</td>
<td align="center">0</td>
<td align="center">0</td>
<td align="center">0</td>
<td align="center">1</td>
</tr>
<tr>
<td>Company3</td>
<td align="center">0</td>
<td align="center">0</td>
<td align="center">0</td>
<td align="center">0</td>
<td align="center">1</td>
</tr>
<tr>
<td>Company4</td>
<td align="center">1</td>
<td align="center">0</td>
<td align="center">0</td>
<td align="center">0</td>
<td align="center">1</td>
</tr>
<tr>
<td>Company5</td>
<td align="center">1</td>
<td align="center">1</td>
<td align="center">0</td>
<td align="center">0</td>
<td align="center">0</td>
</tr>
</tbody>
</table>
<br/>
<input id="btnSubmit" type='button' value='Alert Rows'>


I will include my javascript which at the moment is just counting the total rows so not that much help.

<script type="text/javascript">
$(document).ready(function() {

$("#btnSubmit").click(function(){

var table = $('#table').DataTable();

var rowCount = table.rows()[0].length;

for (var row=0;row<rowCount;row++) {

//Not sure what to do here

}
alert(rowCount); //I need this to be company / companies name from 1st column.
});
});
</script>

Answer

If you want count the number of 1 in your rows, you can use rows().every() to iterate values.

To know the number of 1s for each row you can add the values, try this code:

$(document).ready(function() {

   var table= $('#table').DataTable();

   $('#btnSubmit').click( function () {

       table.rows().every(function(){
         //Sum the values
         var count =  parseInt(this.data()[1]) + parseInt(this.data()[2]) + parseInt(this.data()[3]) + parseInt(this.data()[4]) + parseInt(this.data()[5]);
         //Get Company
         var company = this.data()[0];

         alert("The Company: " + company + " have " + count.toString() + " 1s" );
       });   

    });
});

Result: https://jsfiddle.net/cmedina/7kfmyw6x/88/

Comments