How to add ID to the tr that are generated with Datatables?

Asked

Viewed 500 times

1

Hello!

The Datatables plugin serves to make a table (HTML) after receiving a JSON with the data resulting from a query to the database.

Until then beauty, the problem is that as the table structure is automatically created by Datatables, I cannot assign an ID to each row(tr) of the table.

I need to insert these Ids dynamically, then I can manipulate each line individually.

But I cannot access the creation of this table.

You could help me on how to do this attribution of Ids in the three of the Datatables ?

Code of creation of .

<?php

  // Ler e criar o array de dados
$dados = array();
while( $row_arquivo = mysqli_fetch_array($resultado_arquivos) ) {  
	$dado = array(); 
	$dado[] = utf8_encode(utf8_decode($row_arquivo["cod"]));   //Importante usar o utf8 em campos que vão conter acento pois dara erro no JSON
	$dado[] = utf8_encode(utf8_decode(substr($row_arquivo["empresa"],0,60)));
	$dado[] = utf8_encode(utf8_decode($row_arquivo["tributacao"]));
	$dado[] = utf8_encode(utf8_decode($row_arquivo["cnpj"]));
	$dado[] = "<a class='btn btn-sm btn-success' data-toggle='modal' 'data-target='#modal-alterar-empresas' style='border:1px solid black'>Alterar</a>";
	$dado[] = "<a class='btn btn-sm btn-info' data-toggle='modal' data-target='#modal-vincular-servicos' style='border:1px solid black'>Serviços</a>";
	$dado[] = "<a class='btn btn-sm btn-warning' data-toggle='modal' data-target='#modal-transferir-servicos' style='border:1px solid black'>Serviços</a>";
	$dados[] = $dado;
}

//Cria o array de informações a serem retornadas para o Javascript
$json_data = array(
	"draw" => intval( $requestData['draw'] ),//para cada requisição é enviado um número como parâmetro
	"recordsTotal" => intval( $qnt_linhas ),  //Quantidade de registros que há no banco de dados
	"recordsFiltered" => intval( $totalFiltered ), //Total de registros quando houver pesquisa
	"data" => $dados   //Array de dados completo dos dados retornados da tabela 
);

echo json_encode($json_data);  //enviar dados como formato json


?>

inserir a descrição da imagem aqui

  • 1

    It can be done, but this is very unnecessary because you can take any row of the table without using id.

  • @Sam how does it?

  • I’ll see if I can get an answer.

1 answer

2


You can use the Datatable API to pick up any line, don’t need to add id’s to them.

See below that I apply a red color on the second line:

$(document).ready(function(){
   var tabela = $('#example').DataTable();
   
   var linha2 = tabela.row(1).nodes();
   $(linha2).css("color", "red");
   
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css">
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>

<table id="example" class="display nowrap dataTable dtr-inline collapsed" style="width: 100%;" role="grid" aria-describedby="example_info"><thead><tr role="row"><th class="sorting_asc" tabindex="0" aria-controls="example" rowspan="1" colspan="1" style="width: 119px;" aria-sort="ascending" aria-label="Name: activate to sort column descending">Name</th><th class="sorting" tabindex="0" aria-controls="example" rowspan="1" colspan="1" style="width: 190px;" aria-label="Position: activate to sort column ascending">Position</th><th class="sorting" tabindex="0" aria-controls="example" rowspan="1" colspan="1" style="width: 88px;" aria-label="Office: activate to sort column ascending">Office</th><th class="dt-body-right sorting" tabindex="0" aria-controls="example" rowspan="1" colspan="1" style="width: 34px;" aria-label="Age: activate to sort column ascending">Age</th><th class="sorting" tabindex="0" aria-controls="example" rowspan="1" colspan="1" style="width: 79px;" aria-label="Start date: activate to sort column ascending">Start date</th><th class="dt-body-right sorting" tabindex="0" aria-controls="example" rowspan="1" colspan="1" style="width: 0px; display: none;" aria-label="Salary: activate to sort column ascending">Salary</th></tr></thead><tbody><tr role="row" class="odd"><td tabindex="0" class="sorting_1">Airi Satou</td><td>Accountant</td><td>Tokyo</td><td class=" dt-body-right">33</td><td>2008/11/28</td><td class=" dt-body-right" style="display: none;">$162,700</td></tr><tr role="row" class="even"><td class="sorting_1" tabindex="0">Angelica Ramos</td><td>Chief Executive Officer (CEO)</td><td>London</td><td class=" dt-body-right">47</td><td>2009/10/09</td><td class=" dt-body-right" style="display: none;">$1,200,000</td></tr><tr role="row" class="odd"><td tabindex="0" class="sorting_1">Ashton Cox</td><td>Junior Technical Author</td><td>San Francisco</td><td class=" dt-body-right">66</td><td>2009/01/12</td><td class=" dt-body-right" style="display: none;">$86,000</td></tr><tr role="row" class="even"><td class="sorting_1" tabindex="0">Bradley Greer</td><td>Software Engineer</td><td>London</td><td class=" dt-body-right">41</td><td>2012/10/13</td><td class=" dt-body-right" style="display: none;">$132,000</td></tr><tr role="row" class="odd"><td class="sorting_1" tabindex="0">Brenden Wagner</td><td>Software Engineer</td><td>San Francisco</td><td class=" dt-body-right">28</td><td>2011/06/07</td><td class=" dt-body-right" style="display: none;">$206,850</td></tr><tr role="row" class="even"><td tabindex="0" class="sorting_1">Brielle Williamson</td><td>Integration Specialist</td><td>New York</td><td class=" dt-body-right">61</td><td>2012/12/02</td><td class=" dt-body-right" style="display: none;">$372,000</td></tr><tr role="row" class="odd"><td class="sorting_1" tabindex="0">Bruno Nash</td><td>Software Engineer</td><td>London</td><td class=" dt-body-right">38</td><td>2011/05/03</td><td class=" dt-body-right" style="display: none;">$163,500</td></tr><tr role="row" class="even"><td class="sorting_1" tabindex="0">Caesar Vance</td><td>Pre-Sales Support</td><td>New York</td><td class=" dt-body-right">21</td><td>2011/12/12</td><td class=" dt-body-right" style="display: none;">$106,450</td></tr><tr role="row" class="odd"><td class="sorting_1" tabindex="0">Cara Stevens</td><td>Sales Assistant</td><td>New York</td><td class=" dt-body-right">46</td><td>2011/12/06</td><td class=" dt-body-right" style="display: none;">$145,600</td></tr><tr role="row" class="even"><td tabindex="0" class="sorting_1" style="">Cedric Kelly</td><td>Senior Javascript Developer</td><td>Edinburgh</td><td class=" dt-body-right">22</td><td>2012/03/29</td><td class=" dt-body-right" style="display: none;">$433,060</td></tr></tbody><tfoot><tr><th rowspan="1" colspan="1">Name</th><th rowspan="1" colspan="1">Position</th><th rowspan="1" colspan="1">Office</th><th class="dt-body-right" rowspan="1" colspan="1">Age</th><th rowspan="1" colspan="1">Start date</th><th class="dt-body-right" rowspan="1" colspan="1" style="display: none;">Salary</th></tr></tfoot></table>

The code tabela.row(1).nodes() returns the second element tr table. Rows start with index 0, that is, first line would be tabela.row(0).nodes().

If you want to get the id of the information coming from the database, put on the buttons a data-id='ID_DO_REGISTRO'. So you can take that amount with $(this).data("id") by clicking the buttons.

  • But here’s the thing, I’d like to assign an id to each button, because I’m creating these buttons in PHP. I will show the code part the part I do it. I will update the question.

  • I open a modal that is filled with data, coming from the bank, according to the id of the tr on which I click.

  • And the ID of these <tr> would not be 1,2,3,4... It would be "disorderly" values that would come from the bank.

  • id is the column number "Cód."?

  • No, the column id is a field (called 'code') that I don’t list there.

  • Then I lost rs.... where are the ids (or where they come from) that you want to put in the lines?

  • Ideally this ID would be assigned in PHP.

Show 3 more comments

Browser other questions tagged

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