How to dynamically enable/disable Responsive extension

末鹿安然 提交于 2020-02-24 03:36:06

问题


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?


回答1:


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.




回答2:


Assuming that it is this DataTable plug-in then you can change the responsive setting in your myFunction. First,

var table = $('#example').DataTable(/* your current settings */);

then, in myFunction,

new $.fn.dataTable.Responsive( table, {
    details: true
} );



回答3:


JSFiddle

Well get rid of the obtrusive javascript or use it ( onchange="myFunction()")

$(document).ready(function(){
    var selectedValue;
    $('#selected2').change( function() {
        selectedValue = $(this).val();
        alert(selectedValue);
    });
}); 


来源:https://stackoverflow.com/questions/31486247/how-to-dynamically-enable-disable-responsive-extension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!