Jquery - Popular table using array

2

I need to populate a table with objects received via the database, but I'm not able to pass the contents:

<table id="grid-itens-nota" class="table table-bordered table-hover">
    <thead>
        <tr>                                
         <th>O.S.</th>
         <th>Cód Produto</th>
         <th>Descrição do Produto</th>
         <th>Sit. Trib.</th>
         <th>Unidade</th>
         <th>Valor Unitário</th>
         <th>Valor Total</th>
         <th>Custo Total</th>
         <th>N.C.M.</th>
       </tr>
    </thead>
</table>

The array is sent this way

WithJS:

populaAbaItens(produtos);functionpopulaAbaItens(result){vartable=$("#grid-itens-nota").DataTable({
      data: result,
   });
}
    
asked by anonymous 10.09.2016 / 20:12

1 answer

3

In your specific case, and with searches done Jquery-datatables needs a array and not a objeto , then is to make one more command line to turn objeto into array .

Html:

<table id="grid-itens-nota" class="table table-bordered table-hover">
</table>

Javascript

function populaAbaItens(result) 
{
    var dataSet = [];
    $.each(result, function(index, data)
    {
       dataSet.push([
              data.almoxarifado,
              data.codigo,
              data.descricao,
              data.id, 
              data.ncm,
              data.notaRemessa,
              data.unidade,
              data.valorTotal,
              data.valorUnitario  
       ]);
    }
    var table = $("#grid-itens-nota").DataTable({
          data: dataSet,
          columns: [
                 { title: 'Almoxarifado' },
                 { title: 'Codigo' },
                 { title: 'Descricao' },
                 { title: 'Id' },
                 { title: 'Ncm' },
                 { title: 'Nota Remessa' },
                 { title: 'Unidade' },
                 { title: 'Valor Total' },
                 { title: 'Valor Unitario' }
          ]
    });
}

populaAbaItens(produtos);

Now test this example, notice the changes in tag Table and Javascript .

Functional example:

$(document).ready(function() {    		
  var fs = function(){
    var dataObject = [
      {id:1,name:'A'},
      {id:2,name:'B'},
      {id:3,name:'C'}
    ];
    var dataSet = [];
    $.each(dataObject, function(index,data){
      dataSet.push([data.id,data.name]);
    });
    $('#example').DataTable({
      data: dataSet,
      columns: [
        { title: 'Id' },
        { title: 'Name' }
      ]
    });	
  };
  fs();  		
});
<script type="text/javascript" src="//code.jquery.com/jquery-1.12.3.js"></script>	
    <script type="text/javascript" src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script><tableid="example" class="display" width="100%"></table>
    
11.09.2016 / 03:30