soapergem
soapergem

Reputation: 9989

How do I update DataTables columns (and other properties) dynamically?

There are a few questions here on SO about updating the columns in DataTables dynamically, but they all seem very out of date as they reference deprecated properties like aoColumns.

My code looks something like this:

var oTableOptions = {
    columns: [
        {title: "Column 1", data: "col1"},
        {title: "Column 2", data: "col2"},
        {title: "Column 3", data: "col3"}
    ],
    order: [
        [0, 'desc'],
        [1, 'asc']
    ],
    paging: false,
    searching: false,
    info: false
}

var dt = $('#tableId').DataTable(oTableOptions);

Couple of questions:

  1. How do I update the default sorting order? If I want to dynamically change it to something like [[0, 'asc'], [1, 'asc']] instead (the next time the table is redrawn), how do I do this?

The following code doesn't work, so what am I missing?

dt.order = [[0, 'asc'], [1, 'asc']];
dt.ajax.reload();
  1. How do I rename an existing column? I couldn't find any documented method for doing this. Is there one, or do I just have to use jQuery directly?

  2. How do I add/remove columns?

Upvotes: 2

Views: 7169

Answers (1)

codermapuche
codermapuche

Reputation: 472

var oTableOptions = {
    columns: [
        {title: "Column 1", data: "col1"},
        {title: "Column 2", data: "col2"},
        {title: "Column 3", data: "col3"},
        {title: "Column 4", data: "col4"}
    ],
    order: [
        [0, 'desc'],
        [1, 'asc']
    ],
    paging: false,
    searching: false,
    info: false
}

var dt = $('#tableId').DataTable(oTableOptions);

// Later...

var nTableOptions = {
    columns: [
        {title: "Column 1", data: "col1"},
        {title: "Column 2 n", data: "col2"}, // Rename
        {title: "Column 3", data: "col3"},
        {title: "Column 4", data: "col4"} // New
    ],
    order: [
        [0, 'asc'], // Change
        [1, 'desc'] // Change
    ],
    paging: false,
    searching: false,
    info: false,
    bDestroy: true // Add this property to new setting
}

var dt = $('#tableId').DataTable(nTableOptions);
// Or
var dt = $('#tableId').html("").DataTable(nTableOptions);

Upvotes: 4

Related Questions