【问题标题】:jQuery Datatables: Combining column visibility with individual column filters (text inputs)?jQuery Datatables:将列可见性与单个列过滤器(文本输入)结合起来?
【发布时间】:2019-11-08 04:43:20
【问题描述】:

我正在使用basic column visibilityindividual column searching (text inputs)

问题是当用户向表格中添加以前隐藏的列时,该列的文本字段框不会出现。因此,用户无法过滤该列。

有人知道如何为隐藏列启用过滤器吗?理想情况下,这不会导致清除其他过滤器中的文本的副产品(如果用户确实在其他过滤器中输入了文本)。

这是我的过滤代码:

<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>  

我正在使用这一行来隐藏我想在默认情况下隐藏的列:

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

【问题讨论】:

    标签: javascript jquery datatables filtering visibility


    【解决方案1】:

    我已经使用这个小 sn-p 来隐藏/取消隐藏单个列搜索,与数据表的列可见性事件集成。

    $('#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();
                }
            });
    

    【讨论】:

      【解决方案2】:

      DataTables 中有一个自定义的column-visibility 事件。因此,您可以根据列的当前状态修改 &lt;input&gt; 元素的可见性。

      例如你有&lt;input&gt; 渲染函数,像这样:

      //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;
              });
      };
      

      然后,您可以在列可见性更改时调用它:

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

      此方法的完整演示可能如下所示:

      //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>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-04-06
        • 2019-05-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多