简体   繁体   English

jQuery 数据表:将列可见性与单个列过滤器(文本输入)相结合?

[英]jQuery Datatables: Combining column visibility with individual column filters (text inputs)?

I am using basic column visibility and individual column searching (text inputs) .我正在使用基本列可见性单个列搜索(文本输入)

The problem is that when the user adds a previously-hidden column to the table, the text field box for that column does not appear.问题是当用户向表中添加先前隐藏的列时,该列的文本字段框不会出现。 Thus, the user cannot filter that column.因此,用户无法过滤该列。

Does anyone know how to enable filters for hidden columns as well?有谁知道如何为隐藏列启用过滤器? Ideally, this would not cause a byproduct of clearing the text in the other filters (if the user did enter text in the other filters).理想情况下,这不会导致清除其他过滤器中的文本的副产品(如果用户确实在其他过滤器中输入了文本)。

Here is my filtering code:这是我的过滤代码:

<script type="text/javascript">
$(document).ready(function() {
    // Setup - add a text input to each footer cell
    $('#tableID tfoot th').each( function () {
        var title = $(this).text();

        if ((title != '') && !(title.includes("$"))) {
            // Then the current column is *not* the Action column.          
            $(this).html( '<span style="color: #515151; font-size:15px;"><i>Filter</i></span> <br> <input type="text"  style="margin-top:10px;" placeholder="'+title+'" /> ' );
        }
    } );

    var table = $('#tableID').DataTable();
    // Apply the search
    table.columns().every( function () {
        var that = this;

        $( 'input', this.footer() ).on( 'keyup change', function () {
            if ( that.search() !== this.value ) {
                that
                .search( this.value )
                .draw();
            }
        });
    } );

} );    
</script>  

I am using this line to hide the columns that I want to be hidden from view by default:我正在使用这一行来隐藏我想要在默认情况下隐藏的列:

(table.column('.hideCol')).visible(false);

There's a custom column-visibility event in DataTables. DataTables中有一个自定义的column-visibility事件。 So, you may revise your <input> elements visibility based on current status of the column. 因此,您可以根据列的当前状态来修改<input>元素的可见性。

Eg you have <input> rendering function, like that: 例如,您具有<input>渲染功能,如下所示:

//function to render input elements
const renderTfootInputs =  () => {
        //grab previous inputs into array
        const prevInputs = [];
        dataTable.columns().every(function(){
            prevInputs.splice(this.index(), 1, $(`#example tfoot [colindex="${this.index()}"]`).val());
        });
        //purge <tfoot> row contents
        $('#example tfoot tr').empty()
        //iterate through table columns
        dataTable.columns().every(function(){
            //if the column is visible
            this.visible() ?
            //append corresponding footer <input>
            $('#example tfoot tr').append(`<th><input colindex="${this.index()}" placeholder="${$(this.header()).text()}" value="${prevInputs[this.index()] || ''}"></input></th>`) :
            true;
        });
};

Than, you may call it upon column visibility changes: 然后,您可以在列可见性更改时调用它:

$('#example').on('column-visibility.dt', renderTfootInputs);

Complete demo of this approach might look as follows: 此方法的完整演示如下所示:

 //sample data source const dataSrc = [ {id: 1, title: 'apple', cat: 'fruit'}, {id: 2, title: 'pear', cat: 'fruit'}, {id: 3, title: 'banana', cat: 'fruit'}, {id: 4, title: 'carrot', cat: 'vegie'}, {id: 5, title: 'eggplant', cat: 'vegie'} ]; //datatables initialization const dataTable = $('#example').DataTable({ data: dataSrc, dom: 'Bfrtip', buttons: ['colvis'], columns: ['id','title','cat'].map(header => ({title: header, data: header})), columnDefs: [ {targets: 0, visible: false} ] }); //append blank footer to the table $('#example').append('<tfoot><tr></tr></tfoot>'); //function to render input elements const renderTfootInputs = () => { //grab previous inputs into array const prevInputs = []; dataTable.columns().every(function(){ prevInputs.splice(this.index(), 1, $(`#example tfoot [colindex="${this.index()}"]`).val()); }); //purge <tfoot> row contents $('#example tfoot tr').empty() //iterate through table columns dataTable.columns().every(function(){ //if the column is visible this.visible() ? //append corresponding footer <input> $('#example tfoot tr').append(`<th><input colindex="${this.index()}" placeholder="${$(this.header()).text()}" value="${prevInputs[this.index()] || ''}"></input></th>`) : true; }); }; //initial call of above function renderTfootInputs(); //call that function each time upon column visibility changes $('#example').on('column-visibility.dt', renderTfootInputs); //individual search $('#example').on('keyup', 'tfoot input', function(event){ dataTable.column($(event.target).attr('colindex')).search($(event.target).val()).draw(); }); 
 tfoot input { display: block; } tfoot th { padding-left: 10px !important; } 
 <!doctype html> <html> <head> <script type="application/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script type="application/javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script> <script type="application/javascript" src="https://cdn.datatables.net/buttons/1.5.6/js/dataTables.buttons.min.js"></script> <script type="application/javascript" src="https://cdn.datatables.net/buttons/1.5.6/js/buttons.colVis.min.js"></script> <script type="application/javascript" src="test.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css"> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/1.5.6/css/buttons.dataTables.min.css"> </head> <body> <table id="example"></table> </body> </html> 

I have worked with this small snippet to hide/Unhide the Individual Column Search, Integrated with Column Visibility Event of Datatables.我已经使用这个小片段来隐藏/取消隐藏单个列搜索,与数据表的列可见性事件集成。

$('#table').on( 'column-visibility.dt', function ( e, settings, column, state ) {
            columnv = settings.aoColumns[column].bVisible;
            if(columnv === false){
                 $('#table').find("tr.filters th:eq('"+column+"')").hide();
            }else{
                 $('#table').find("tr.filters th:eq('"+column+"')").show();
            }
        });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM