Search code examples
jsondatatablestabletools

Datatables TableTools add/get json object from hidden column on row click


I'm trying to add on datatable initialization to a hidden column a json object data. If I stringify the json data to the hidden column the "json object" gets cut.

res = JSON.parse(JSON.stringify(res).replace(/%3C/g,'%3C%20')); //res is the json object from server
var result = res.items;
var linesArray = []; //this is used further to my buildatatable function where i transform each array position to a datable row
var columnsArray = [];

columnsArray.push(
    {"sTitle": "jsonobj"},//hidden column
    {"sTitle": "Column one"},
    {"sTitle": "Column two"},
    {"sTitle": "Column tree"}, 
    {"sTitle": "Column four"}, 
    {"sTitle": "Column five"});     

//update FIRST PROBLEM was no problem :)

$.each(result, function(index, items){ //loop through to json objects to get values

linesArray.push([JSON.stringify(items),//Json object stringified that gets cut, i made this so i can access further the json on row click
                  decodeValue(items.xptoone),
                  decodeValue(items.xptotwo), 
                  decodeValue(items.xptotree), 
                  decodeValue(items.xptofour), 
                  decodeValue(items.xptofive)]); 
 });

//SECOND PROBLEM HOW TO GET THAT JSON OBJECT WITH oTableTools

//these are options that are concatenated to other options to datatable initialization   
 var options =  { 
            "oTableTools": {
                              "sRowSelect": "single",
                              "sSelectedClass": "row_selected",
                              "fnRowSelected": function (node) {

                                   //SECOND PROBLEM

                              }
                            },
            "columnDefs": [ //Hidden column jsonobj
                              {
                                  "targets": [ 0 ],
                                  "visible": false
                              }
                            ]
            };      

//this function initializes the datatable with specific columns and rows                
buildDataTable("mytable",columnsArray,linesArray,options);

Solution

  • You can access the JSON data in fnRowSelect as follows:

    "fnRowSelected": function(node){
        var data = $('#mytable').DataTable().row(node).data();
        console.log(data[0]);     
    }