I have a project where users need to be able to select whether or not the accompanying script activates Responsive extension of jQuery DataTables.
I want to add a dropdown menu in HTML that lets users choose whether option responsive
is set to true
or false
in dataTable()
initialization options.
I tried to add a separate function to select the value and used a global variable to get it to the dataTable()
function but couldn't get that to work.
JavaScript:
$(document).ready(function(){
$("#example").dataTable({
"responsive": false,
"processing": false,
"serverSide": true,
"ajax": "scripts/university.php",
"columns": [
// ID
null, ........
*HTML**
<select id="selected2" onchange="myFunction()">
<option value="true">true</option>
<option value="false">false</option>
</select>
I tried adding a document.getElementById
clause as the first line in the dataTable function but couldn't make it work.
What can I add to the existing function to make responsive
option user selectable from the list on the HTML page?
SOLUTION
You need to destroy table to re-initialize it and enable/disable Responsive extension.
var dtOptions = {
responsive: true
};
var table = $('#example').DataTable(dtOptions);
$('#ctrl-select').on('change', function(){
dtOptions.responsive = ($(this).val() === "1") ? true : false;
$('#example').DataTable().destroy();
$('#example').removeClass('dtr-inline collapsed');
table = $('#example').DataTable(dtOptions);
});
NOTES
When the table is destroyed, Responsive extension leaves some classes (dtr-inline
, collapsed
), so I remove them manually before initializing the table again.
Also I suggest having all options in a separate object dtOptions
to make re-initialization easier, that way you just need to toggle one option responsive
.
DEMO
See this jsFiddle for code and demonstration.