Style a checkbox in datatable columns

1.6k Views Asked by At


I have a datatable from ajax source. I want to display a checkbox in one column based on its value.

If the value is active, checkbox should be checked, otherwise it remains unchecked.

I am using Switchery JS to stylize the checkbox. It works fine in normal HTML body, but not inside a datatable column.

Here is the fiddle:

https://jsfiddle.net/sohal/gfuuazxL/4/

1

There are 1 best solutions below

0
On

The problem is that you are doing the Switchery' before the dataTable is populated with data. And even if you did it after, you would still end up not having Switcherys on hidden rows, i.e on page #2, #3 and so on.

So you must initialise Switchery after the dataTable is initialised and do the Switchery on all rows. You can do this in the initComplete() callback, and iterate over all rows by using the API every() method :

$(document).ready(function() {
  var table = $('#datatable-buttons').DataTable({
    initComplete : function() {
       this.api().rows().every( function ( rowIdx, tableLoop, rowLoop ) {
         this.nodes().to$().find('.js-switch').each(function(i, e) {
           var switchery = new Switchery(e, {
             color: '#26B99A'
           })
         })
       })  
    },
    ...//rest of the options
  })
})

forked fiddle -> https://jsfiddle.net/jpkysyp1/