Isaac
Isaac

Reputation: 277

jQuery Datatable Conditional Settings

I am wondering if there is a way to conditionally set properties on a jQuery DataTable and thus avoid repeating nearly identical table conversion calls with duplicate properties.

For example, I have a table that I want to provide an Excel export button on if a certain boolean is true, but don't provide it if that boolean is false.

if blnExport {
    $('#tblDetail').DataTable({
        bPaginate: false,
        aaSorting: [],
        language: { emptyTable: "No Results Found" },
        dom: 'Bfrtip',
        buttons: [
        {
            extend: 'excel',
            text: 'Export to Excel',
            exportOptions: {
                columns: [0, 1, 2, 3, 4, 5, 6, 7]
            } 
        }]
    });
}    
else {
    $('#tblDetail').DataTable({
        bPaginate: false,
        aaSorting: [],
        language: { emptyTable: "No Results Found" }
    });
}

Is there a way to accomplish this with one conversion call? Thanks.

Upvotes: 1

Views: 2206

Answers (1)

Lajos Arpad
Lajos Arpad

Reputation: 76545

Let's suppose you have a function like this:

function myFunction(params) {
    //Do something
}

Let's consider this example:

var input = {
    a: 1;
};

if (Math.floor(Math.random() * 2)) {
    input.b = 2;
}

myFunction(input);

As you can see in the example, a is always a member of input, but we randomize whether b should be in it. Basically, the idea is to:

  • create the input object with what you surely need
  • check what is needed and add it
  • pass it to the function

Let's apply this to your specific case:

var input = {
    bPaginate: false,
    aaSorting: [],
    language: { emptyTable: "No Results Found" }
};

if (blnExport) {
    input.dom = 'Bfrtip';
    input.buttons = [{
        extend: 'excel',
        text: 'Export to Excel',
        exportOptions: {
            columns: [0, 1, 2, 3, 4, 5, 6, 7]
        } 
    }];
}
$('#tblDetail').DataTable(input);

Upvotes: 1

Related Questions