Search code examples
jquerydatatablestargetcolumndefinition

How can I define the targets of columnDefs in datatables as "last"?


My target is right now set to column 5:

"columnDefs": [{
  "render": function (data, type, row) {
    return data;
  },
  "targets": 5
}],

What I want to do is, instead of targeting it to a specific number, I want to target it to the last column.

What I need is something like this:

"columnDefs": [{
  "render": function (data, type, row) {
    return data;
  },
  "targets": last
}],

Solution

  • According to the documentation you can provide an integer for the targets which specifies the index of the column to use.

    This columnDefs.targets option provides the information required by DataTables for which columns in the table the column definition object should be applied.

    It can be:

    • 0 or a positive integer - column index counting from the left
    • A negative integer - column index counting from the right
    • A string - class name will be matched on the TH for the column (without a leading .)
    • The string "_all" - all columns (i.e. assign a default)

    Note the second point; you can provide a negative integer to start the index from the right, so -1 would be the last column.

    "columnDefs": [{
      "render": function(data, type, row) {
        return data;
      },
      "targets": -1
    }],