Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Index column to dataTable

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..!

like image 221
Cijo V J Avatar asked Mar 09 '15 07:03

Cijo V J


2 Answers

Try this.

"render": function ( data, type, full, meta ) {
    return  meta.row + 1;
} },
like image 88
Atul Kumar Avatar answered Sep 28 '22 09:09

Atul Kumar


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.

like image 38
dimyG Avatar answered Sep 28 '22 09:09

dimyG