Search code examples
javascriptdatatablestabletools

how to add parameters in a javascript object (DataTables)?


I want to build a DataTable with the following parameters.

var table3 = $('#msg').dataTable({
    "scrollY":          calcDataTableHeight(),
    "scrollCollapse":   true,
    "paging":           false,
    "bInfo":            false,
    "order":            [[0, "desc"]],
    "dom": "Tfrtip",
    "ajax": {
        "url": "includes/DataTables-1.10.4/extensions/Editor-1.3.3/php/table.msg.php",
        "data": function (d){
            d.cat = cat;
        },
        "type": "POST"
    }
});

Some Parameters depend on Variables. So if needed I want to add these to the object.

if (buttons == true) {
add this to table 3
        "tableTools": {
        "sRowSelect": "os",
        "aButtons": [
            { "sExtends": "editor_create", "editor": editor },
            { "sExtends": "editor_edit",   "editor": editor },
            { "sExtends": "editor_remove", "editor": editor }
        ]
    }

How can I do this? I tried a lot, but nothing works.


Solution

  • Build your options as an object and then pass it to DataTables after you're done.

    For example:

     var options = {
        "scrollY":          calcDataTableHeight(),
        "scrollCollapse":   true,
        "paging":           false,
        "bInfo":            false,
        "order":            [[0, "desc"]],
        "dom": "Tfrtip",
        "ajax": {
            "url": "includes/DataTables-1.10.4/extensions/Editor-1.3.3/php/table.msg.php",
            "data": function (d){
                d.cat = cat;
            },
            "type": "POST"
        }
    };
    
    if (buttons == true) {
       options['tableTools'] = {
          "sRowSelect": "os",
          "aButtons": [
             { "sExtends": "editor_create", "editor": editor },
             { "sExtends": "editor_edit",   "editor": editor }
          ]
       };
    
       if (showRemoveBtn) {
          options['tableTools']['aButtons'].push(
             { "sExtends": "editor_remove", "editor": editor }
          );
       }
    }
    
    var table3 = $('#msg').dataTable(options);
    

    It could also be done with $.extend, if you want.