Datatable hide and show rows based on a button click event

前端 未结 2 1393
感情败类
感情败类 2021-01-31 05:16

So I have this datatable that is generated by php dynamically once. But once it\'s loaded, I don\'t want to reload the whole table since there\'s only a small javascript if stat

相关标签:
2条回答
  • 2021-01-31 05:42

    Yes, it is indeed possible, but you will need a different approach. Hiding rows with jQuery and not through dataTables itself is generally a bad idea, since dataTables is not aware of changes made to the original <table> element in DOM. There is no "somewhere-in-code-another-script-has-hidden-a-row"-event dataTables can hook into. That is why dataTables seems to "forget" changes, it is simply not aware of those changes, and the dataTables internals stay untouched.

    So use a custom filter instead. The following small piece of code does what you want - hiding all rows having a data-user attribute different than 5. It works across sorting and pagination. The last piece of code is an example of a reset-button.

    $("#hide").click(function() {
        $.fn.dataTable.ext.search.push(
           function(settings, data, dataIndex) {
              return $(table.row(dataIndex).node()).attr('data-user') == 5;
           }
        );
        table.draw();
    });    
    $("#reset").click(function() {
        $.fn.dataTable.ext.search.pop();
        table.draw();
    });
    

    demo -> http://jsfiddle.net/d5hre2ux/

    0 讨论(0)
  • 2021-01-31 05:46

    According to this https://datatables.net/examples/plug-ins/range_filtering.html it is possible to use data parameter to filter by any value shown on the table.

    $("button").click(function() {
        $.fn.dataTable.ext.search.push(
          function(settings, data, dataIndex) {
              return data[3] != "63";
            }
        );
        table.draw();
    });  
    
    0 讨论(0)
提交回复
热议问题