I'm implementing switchery into datatable in this way
UPDATE
var table = $('#table').DataTable({
pageLength: 25,
responsive: true,
deferRender: true,
stateSave: false,
info: false,
ordering: false,
dom: 'lTfgt<"float-left"i>p',
ajax: {
"url": "../src/routes.php",
"type": "POST",
"async":true,
"dataType": "json",
"data": function(d) {
d.call = "data-vol";
d.dataform = $('#filtroForm').serialize();
d.market = JSON.stringify($('#jstree_topmarket').jstree("get_selected"));
return d;
}
},
language: {
"url": "assets/js/plugins/dataTables/it_IT.txt"
},
"fnDrawCallback": function() {
var elems = Array.prototype.slice.call(document.querySelectorAll('.js-switch'));
elems.forEach(function(html) {
var switchery = new Switchery(html, { size: 'small' });
});
}
});
and seems ok
but when I switch to page 2 and then come back to page 1, I have this result
EDIT
Replacing fnDrawCallback with initComplete seems not working
I would recommend using an
initComplete
function instead ofdrawCallback
. This will avoid the problem you are seeing where you get new sliders added every time there is another draw event in your DataTable.To access the checkbox nodes from
initComplete
you can use this:The first line of the function uses the Datatables API to access every node in the table.
allNodes
is a collection of<td>
nodes - so then we have to select only those which contain a child node which uses yourjs-switch
class.Since we already have jQuery, I chose to use its iterator
$.each()
to iterate over al these checkbox nodes, to create the switchery object.Update:
Here is the full DataTable I am using to test with:
My test data is in a JavaScript variable: