DataTables example Index column

A fairly common requirement for highly interactive tables which are displayed on the web is to have a column which with a 'counter' for the row number. This column should not be sortable, and will change dynamically as the ordering and searching applied to the table is altered by the end user.

This example shows how this can be achieved with DataTables, where the first column is the counter column, and is updated when ordering or searching occurs. This is done by listening for the orderDT and searchDT events emitted by the table. When these events are detected the column().nodes()DT method is used to get the TD/TH nodes for the target column and the each() helper function used to iterate over each, which have their contents updated as needed. Note that the filter and order options are using in the column()DT method to get the nodes in the current order and with the currently applied filter.

NamePositionOfficeAgeSalary
NamePositionOfficeAgeSalary
1 Airi Satou Accountant Tokyo 33 $162,700
2 Angelica Ramos Chief Executive Officer (CEO) London 47 $1,200,000
3 Ashton Cox Junior Technical Author San Francisco 66 $86,000
4 Bradley Greer Software Engineer London 41 $132,000
5 Brenden Wagner Software Engineer San Francisco 28 $206,850
6 Brielle Williamson Integration Specialist New York 61 $372,000
7 Bruno Nash Software Engineer London 38 $163,500
8 Caesar Vance Pre-Sales Support New York 21 $106,450
9 Cara Stevens Sales Assistant New York 46 $145,600
10 Cedric Kelly Senior Javascript Developer Edinburgh 22 $433,060
Showing 1 to 10 of 57 entries

The Javascript shown below is used to initialise the table shown in this example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
$(document).ready(function() {
    var t = $('#example').DataTable( {
        "columnDefs": [ {
            "searchable": false,
            "orderable": false,
            "targets": 0
        } ],
        "order": [[ 1, 'asc' ]]
    } );
 
    t.on( 'order.dt search.dt', function () {
        t.column(0, {search:'applied', order:'applied'}).nodes().each( function (cell, i) {
            cell.innerHTML = i+1;
        } );
    } ).draw();
} );

In addition to the above code, the following Javascript library files are loaded for use in this example: