4

I'm trying to set a custom property and be able to access/edit it later. Is this even possible, i've seen in older version one can use fnSettings but how do I use this in 1.10.5?

$('#table').DataTable({
        customProp: 'Hello World'
});

Then with a button click I thought I could do the following:

$('.test').on('click', function(e){
      var table = $('#table').DataTable();
      console.log(table.settings.oInit.customProp);
 }

However I get: Uncaught TypeError: Cannot read property 'customProp' of undefined

Does anyone know how I can do this?

davidkonrad
  • 83,997
  • 17
  • 205
  • 265
bstras21
  • 981
  • 3
  • 11
  • 32

3 Answers3

1

You can use jQuery data() method to store data in associated element. For example:

$('#table').data('customProp', 'Hello World');

Later you can retrieve it as shown below:

$('.test').on('click', function(e){
    console.log($('#table').data('customProp'));
}
Gyrocode.com
  • 57,606
  • 14
  • 150
  • 185
1

For some reason, table.settings.oInit is accessible upon initialisation only. After initialisation, neither table.settings nor $("#table").DataTable().settings holds oInit (or a function to access initialisation values). A workaround is to store oInit in a variable :

var init;

$('#example').DataTable({
   customProp: 'Hello World',
   initComplete: function(settings) { 
       init = settings.oInit;
   }
});

Now you can do this :

alert(init.customProp);

demo (1.10.5) -> http://jsfiddle.net/ajLe1484/

Apparently dataTables passes one object in the callbacks, and a different somehow "cleaned up" object by the table instance. I am a little bit surprised dataTables does that. Tested it with 1.10.x too - the behaviour was the same, so it is not because oInit has been sunsetted by 1.10.5.

davidkonrad
  • 83,997
  • 17
  • 205
  • 265
1

For DataTables 1.10.10 and newer the following will work:

$('#table').DataTable({
        customProp: 'Hello World'
});

console.log($('#table').DataTable().init().customProp);
Alex Art.
  • 8,711
  • 3
  • 29
  • 47