Add Index column to dataTable
Asked Answered
S

11

9

Suppose I have the following json to display in my DataTable:

 // JSON structure for each row in this example:
    //   {
    //      "engine": {value},
    //      "browser": {value},
    //      "platform": {value},
    //      "version": {value},
    //      "grade": {value}
    //   }
    $('#example').dataTable( {
      "ajaxSource": "sources/objects.txt",
      "columns": [
        { "data": "engine" },
        { "data": "browser" },
        { "data": "platform" },
        { "data": "version" },
        { "data": "grade" }
      ]
    } );

What I want is, Add an Index Column to this data table for number the row. Something like this :

 "columns": [
        {"data" : "Index"},      <------- this should number my rows 
        { "data": "engine" },
        { "data": "browser" },
        { "data": "platform" },
        { "data": "version" },
        { "data": "grade" }
      ]

Note: I don't have any Index as data passed in my Json(Although I can do that, is there any better solution to handle this in my Javascript itself? )

Help appreciated..!

Sligo answered 9/3, 2015 at 7:25 Comment(0)
S
7

Try this.

"render": function ( data, type, full, meta ) {
    return  meta.row + 1;
} },
Secede answered 22/11, 2018 at 12:20 Comment(0)
T
3

The concept is that you have to create the initial "Index" values either in javascript or in the server. The values can be zero or just empty strings or whatever (there is no need to calculate a counter or something). For example you can create an index column in javascript after you have received the data:

for (var i=0; i<data.length; i++){
        data[i].index = 0;
    }

So now that you have the index column in your data you declare it as the first column of your table:

$('#example').dataTable( {
  .....
  "columns": [
    { "data": "index" },
    { "data": "engine" },
    { "data": "browser" },
    { "data": "platform" },
    { "data": "version" },
    { "data": "grade" }
  ]
} );

Now the index values are all 0. To create the real index values that will be shown in the table you need to add an event handler that listens to the ordering and searching of the table. On these events the real index values will be calculated as described in the datatables example:

datatable_object.on( 'order.dt search.dt', function () {
    datatable_object.column(0, {search:'applied', order:'applied'}).nodes().each( function (cell, i) {
        cell.innerHTML = i+1;
    } );
} ).draw();

When the table is searched or ordered (ordering is done by default when the table is created - see default value of the order option), the innerHtml of the "Index" cells will be calculated based on the index of the row.

Tephrite answered 27/7, 2016 at 12:1 Comment(0)
B
2

Need to use DT_RowIndex for indexing rows. Like this - ## Heading ##

"columns": [
{ "data": 'DT_RowIndex'}, // row index
{ "data": "engine" },
{ "data": "browser" },
{ "data": "platform" },
{ "data": "version" },
{ "data": "grade" }
]
Bogeyman answered 20/4, 2021 at 4:58 Comment(0)
R
1

Just add the code below to your datatables

{ 'data': 'id', defaultContent: '' },
"columnDefs": [   ////define column 1 , make searchable false 
    {
        "searchable": false,
        "orderable": false,
        "targets": 0

    },

Below is the updated code:

 var table=$('#example').dataTable( {
     "ajaxSource": "sources/objects.txt",
     "columns": [
         { 'data': 'id', defaultContent: '' },
         { "data": "engine" },
         { "data": "browser" },
         { "data": "platform" },
         { "data": "version" },
         { "data": "grade" },
     "columnDefs": [   ////define column 1
         {
             "searchable": false,
             "orderable": false,
             "targets": 0
         },

     ]
});

And the following line will add number to your id(index) column:

if (t.data().length != 0) {
    t.on('order.dt search.dt', function () {
        t.column(0, { search: 'applied', order: 'applied' }).nodes().each(function (cell, i) {
            cell.innerHTML = i + 1;
            t.cell(cell).invalidate('dom');
        });
    }).draw();

Live example: http://live.datatables.net/woboviqi/2/edit

Rodie answered 9/1, 2018 at 5:38 Comment(0)
F
0

You can use unshift()

"columns": [
    { "data": "engine" },
    { "data": "browser" },
    { "data": "platform" },
    { "data": "version" },
    { "data": "grade" }
].unshift({"data" : "Index"})

Or by using an temp array

var cols = [{
    "data": "engine"
}, {
    "data": "browser"
}, {
    "data": "platform"
}, {
    "data": "version"
}, {
    "data": "grade"
}];

cols.unshift({
    "data": "Index"
})

....
"columns": cols
Farmergeneral answered 9/3, 2015 at 7:27 Comment(1)
It says Requested Unknown parameter "Index" for row 0. And the Index numbers are not displayed.Sligo
P
0

Have a look on this URL: Data table Index column

It might help you.

Protector answered 9/3, 2015 at 9:17 Comment(0)
J
0

Here is my code you can refer to:

  1. My DataTable is complete custom.
  2. I'm fetching data from the database using Ajax and CodeIgniter.

HTML

<table width="100%" class="table table-striped table-hover" id="table_id_dataTable">
  <thead>
    <tr>
      <th>Sr No</th>
      <th>Column 2</th>
      <th>Column 3</th>
      <th>Column 4</th>
      <th>Column 5</th>
    </tr>
  </thead>
  <tfoot>
    <tr>
      <th>Sr No</th>
      <th>Column 2</th>
      <th>Column 3</th>
      <th>Column 4</th>
      <th>Column 5</th>
    </tr>
  </tfoot>
  <tbody>

  </tbody>
</table>

JS Script

var temp_table = $('#table_id_of_dataTable').DataTable({
  "language": {
    "zeroRecords": "No records found."
  },
  "ajax": {
    "type": "POST",
    "url": "<?php echo base_url('Controller/method'); ?>"
  },
  "responsive": true,
  "columnDefs": [
    {
     "searchable": false,
     "orderable": false,
     "targets": 0
    }
  ],
  "order": [
    [1, 'asc']
  ],
  "columns": [
    { "data": null }, // <-- This is will your index column
    { "data": "column_2_element_name_given_in_controller" }, 
    { "data": "column_3_element_name_given_in_controller" }, 
    { "data": "column_4_element_name_given_in_controller" }, 
    { "data": "column_5_element_name_given_in_controller" }
  ]
});

// Here we create the index column in jquery datatable
temp_table.on('order.dt search.dt', function() {
  temp_nuggets_table.column(0, {
    search: 'applied',
    order: 'applied'
  }).nodes().each(function(cell, i) {
    cell.innerHTML = i + 1;
  });
}).draw();

Hope it helps!

Jehu answered 21/10, 2016 at 13:8 Comment(0)
D
0

That is simple... This work for me.

Cell: function ( data, type, full, counter ) {
        return  data.index + 1
}
Decaffeinate answered 30/7, 2019 at 16:32 Comment(0)
C
0

enter link description here

Try this: 
var table=$('#example').dataTable( {
     "ajaxSource": "sources/objects.txt",
     "columns": [
        {
                    "data": null, "render": function (data, type, full, meta) {
                        return meta.row + 1;
                    }
         },
         { "data": "engine" },
         { "data": "browser" },
         { "data": "platform" },
         { "data": "version" },
         { "data": "grade" }
     
});

table.on('order.dt search.dt', function () {
        table.column(0, { search: 'applied', order: 'applied' }).nodes().each(function (cell, i) {
            cell.innerHTML = i + 1;
        });
    }).draw();
Canterbury answered 17/12, 2019 at 2:53 Comment(0)
C
0

enter link description here

Try this: 
var table=$('#example').dataTable( {
     "ajaxSource": "sources/objects.txt",
     "columns": [
        {
                    "data": null, "render": function (data, type, full, meta) {
                        return meta.row + 1;
                    }
         },
         { "data": "engine" },
         { "data": "browser" },
         { "data": "platform" },
         { "data": "version" },
         { "data": "grade" }
     
});
Canterbury answered 17/12, 2019 at 2:57 Comment(0)
I
0

You can set below for add index column with id

let oTable =   $('.dataTable').DataTable({
                processing: true,
                serverSide: true,
                lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "Show All"]],
                ajax: {
                    url: "{{route('route')}}",
                    type:'POST', headers:{  'X-CSRF-TOKEN': '{{ csrf_token() }}' },
                    data: function (d) {
                        d.date = $('input[name=date]').val();
                    }
                },
                columns: [
                    {"data": 'DT_RowIndex', "name": 'DT_RowIndex', searchable: false},
                    {data: 'date', name: 'date', searchable: true},
                ]
            });

I use this in my laravel code

Interlocution answered 4/1, 2024 at 5:0 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Achromatism

© 2022 - 2025 — McMap. All rights reserved.