2

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?

1 Answer 1

4

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);

Sign up to request clarification or add additional context in comments.

1 Comment

So in other words... destroy the entire table and re-draw it from scratch? That clearly isn't ideal, because that means I have to have all of the same initial table options available, in order to re-create the table. Do I really have to do something so drastic? I was hoping for some simpler way of just updating properties.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.