SebCollard
SebCollard

Reputation: 332

How to add id in TD tag?

I'm using DataTables plugins (I'm a beginner) and I would like to add an 'id' in the <td> HTML tag. I did what's in this post but it's not what I want.

I saw this post too but I don't know how to use this code.

JS :

$('#datatable').dataTable({
    "sPaginationType" : "full_numbers",
    "createdRow" : function ( row, data_use, dataIndex ) {
        $(row).attr('id', dataIndex);
    },
    data : data_use,
    columns : column_name,
    dom : 'Bfrtip',
    select : 'single',
    responsive : true,
    altEditor : true,
    destroy : true,
    searching: true,
    buttons : [{
        extend : 'selected',
        text : 'Edit',
        name : 'edit'
    }],
});

Upvotes: 1

Views: 3600

Answers (1)

JoshG
JoshG

Reputation: 6735

You can do this by adding a columnDefs array to your DataTable configuration and adding a createdCell function. For example:

$(document).ready(function() {
  var table = $('#example').DataTable({
    'columnDefs': [{
      'targets': "_all",    // this will invoke the below function on all cells
      'createdCell': function(td, cellData, rowData, row, col) {
        // this will give each cell an ID
        $(td).attr('id', 'cell-' + cellData);
      }
    }]
  });

Run the snippet below to see a complete example. You can right click on a cell (i.e., a td) and click "Inspect" to see the id attribute that is added to each cell.

$(document).ready(function() {
  var table = $('#example').DataTable({
    'columnDefs': [{
      'targets': "_all",
      'createdCell': function(td, cellData, rowData, row, col) {
        $(td).attr('id', 'cell-' + cellData);
      }
    }]
  });

  // Add some data to the table
  table.row.add(['Airi Satou', 'Accountant', 'Tokyo', '5407', '2008/11/28', '$162,700']).draw();

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdn.datatables.net/r/dt/dt-1.10.9/datatables.min.js"></script>
<link href="https://cdn.datatables.net/r/dt/dt-1.10.9/datatables.min.css" rel="stylesheet" />
<table id="example" class="display" cellspacing="0" width="100%">
  <thead>
    <tr>
      <th>Name</th>
      <th>Position</th>
      <th>Office</th>
      <th>Extn.</th>
      <th>Start date</th>
      <th>Salary</th>
    </tr>
  </thead>
  <tfoot>
    <tr>
      <th>Name</th>
      <th>Position</th>
      <th>Office</th>
      <th>Extn.</th>
      <th>Start date</th>
      <th>Salary</th>
    </tr>
  </tfoot>
</table>

Upvotes: 6

Related Questions