Datatables highlight line with higher percentage

Asked

Viewed 676 times

3

In my system I have a table mounted by DataTables. Data is received from the server via Ajax.

Example of the data structure loaded in the table:

DDD | Processed | Approved | Percentage           |

11 - 19 | 2.660 | 574 | 21.58%                 |

21 - 28 | 2.249 | 298 | 13.25%                 |




And the way I’m using the configuration parameters:

var oTable = $('#tblList').dataTable({
        "aaData": dtData,
        "bFilter": true,
        "bInfo": true,
        "bStateSave": false,
        "oLanguage": {
            "sUrl": "pt.txt"
        },
        "bJQueryUI": true,
        "bProcessing": true,
        "bDestroy": true,
        "bPaginate": true,
        "bLengthChange": false,
        "sPaginationType": "full",
        "aLengthMenu": [[10], [10]],
        "dom": '<"top"iflp<"clear">>rt<"bottom"iflp<"clear">>',
        "bAutoWidth": false,
        "aoColumns": [{ "sWidth": "50%" }, { "sWidth": "15%" }, { "sWidth": "15%" }, { "sWidth": "20%" }],
        "aoColumnDefs":
        [{ "sTitle": "DDD", "bSortable": true, "sName": "ddd", "aTargets": [0] },
         { "sTitle": "Processados", "bSortable": true, "sName": "Processados", "aTargets": [1] },
         { "sTitle": "Aprovados", "bSortable": true, "sName": "Aprovados", "aTargets": [2] },
         { "sTitle": "Percentual de Aprovação", "bSortable": true, "sName": "Percentual de Aprovação", "aTargets": [3] }]
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>




I need to know some way to highlight the line that has the highest percentage, in this case (21.58%). Using a background color, or text color, font, etc.

  • I don’t quite understand what you’re wanting, you want to highlight the color in the Datatable class? or in some grid ?

  • I want to highlight the Datatable line. Using some function or configuration of the https://datatables.net plugin/

3 answers

1

You can scroll through the entire table looking for the highest value and highlight it.

Sort of like this:

maiorValor = primeiroValorTabela;
$(tabela).each(function(i) {
    var valorAtual = $(this).val();
    if (valorAtual > maiorValor) {
        maiorValor = valorAtual;
    }
});

Then you add the class to highlight

$(maiorValor).addClass('destaque');

Css:

td.destaque {
    background-color: yellow !important;
}

Note: This code above doesn’t work, it’s just a "sketch" for you to get an idea.

1

You can make a code javascript to solve the problem:

// Instanciando a tabela
$(document).ready(function() {
  var tabela = $('#exemplo').DataTable( {
   "order": [[ 5, "desc" ]] // Esta linha apenas ordena a tabela pela coluna 5
} );

var max = maxValue(table);

// Verificando quais colunas tem o valor mais alto encontrado
var indexes = table.rows().eq( 0 ).filter( function (rowIdx) {
  return table.cell( rowIdx, 5 ).data() === max ? true : false;
} );

// Adicionando o estilo CSS a linha
table.rows( indexes )
    .nodes()
    .to$()
    .addClass('destaque');
} );

// Função para pegar o valor máximo usando o método Sort da API
function maxValue(table, indice) {
    var valArray = table.column(indice)
                               .data()
                               .sort();
    return valArray[0];
}

The CSS style you can create the way you prefer, I made a very simple:

<style type="text/css" class="init">
  .destaque{
    color:red;
  }
</style>

If there are columns with the same maximum value both will be highlighted

1

You can scroll through all rows of the table with the function fnRowCallback, store the values in an array, then filter the highest value and highlight the line, see the example below:

//Array para armazenar todos os valores da coluna
var vals  = [];
$('#tblList').dataTable({
//função percorre todas as linhas antes de renderizar
fnRowCallback:function(nRow, aData, iDisplayIndex, iDisplayIndexFull){
  var val = parseFloat(aData[3]); // transforma texto da terceira coluna em float
  vals[iDisplayIndex] = val;//coloca no Array
  $(nRow).data('max',val);//Define o atributo data de cada linha
}
});
//Filtra o maior valor do Array
var max = vals.reduce(function(a,b){
  return Math.max(a,b);
});
/*
* Percorre todas as linhas da tabela
* comparando se o atributo data da linha é igual
* ao valor máximo e destaca a linha, neste caso se
* houverem valores iguais todas as linhas serão destacadas
*/
$('#tblList tbody tr').each(function(){
  if($(this).data('max') == max){
     $(this).children('td').css('background-color','yellow');
  }
});
<link href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>


<table id="tblList">
<thead>
  <tr>
    <th>DDD</th>
    <th>Processadores</th>
    <th>Aprovados</th>
    <th>Percentual</th>
  </tr>
</thead>
<tbody>
  <tr>
    <td>11 - 19</td>
    <td>2.660</td>
    <td>574</td>
    <td>21.58%</td>
  </tr>
   <tr>
    <td>11 - 19</td>
    <td>2.660</td>
    <td>574</td>
    <td>21.59%</td>
  </tr>
  
  <tr>
    <td>21 - 28</td>
    <td>2.249</td>
    <td>298</td>
    <td>13.25%</td>
  </tr>
 <tr>
    <td>21 - 28</td>
    <td>2.249</td>
    <td>298</td>
    <td>21.59%</td>
  </tr>
  
</tbody>
</table>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.