使用DataTable.js在顶部过滤器的JS数据的单个列搜索过滤器

时间:2019-05-29 14:51:36

标签: javascript jquery datatables

我无法将过滤器选择放在顶部。我如何达到目标?

我坚持使用initComplete选项,因为它是在DataTable完全初始化且API方法可以安全调用后才被触发的。

我还将在哪里使列下拉值变得唯一

const dataSet = [
      ["Tiger Nixon", "System Architect", "Edinburgh", "5421", "2011/04/25", "$320,800"],
      ["Garrett Winters", "Accountant", "Tokyo", "8422", "2011/07/25", "$170,750"],
      ["Ashton Cox", "Junior Technical Author", "San Francisco", "1562", "2009/01/12", "$86,000"],
    ];

    const dataTable = $('#example').DataTable({
        data: dataSet,
        dom: 't',
        columns: ['Name', 'Job Title', 'Location', 'Id', 'Hire Date', 'Salary'].map(header => ({
            title: header
          })),
        initComplete: function () {
          //purge existing <tfoot> if exists
          $('#example tfoot').remove();
          //append new footer to the table
          $('#example').append('<tfoot><tr></tr></tfoot>');
          //iterate through table columns
          this.api().columns().every(function () {
            //append <select> node to each column footer inserting 
            //current column().index() as a "colindex" attribute
            $('#example tfoot tr').append(`<th><select colindex="${this.index()}"></select></th>`);
            //grab unique sorted column entries and translate those into <option> nodes
            const options = this.data().unique().sort().toArray().reduce((options, item) => options += `<option value="${item}">${item}</option>`, '<option value=""></option>');
            //append options to corresponding <select>
            $(`#example tfoot th:eq(${this.index()}) select`).append(options);
          });
        }
      });

    $('#example').on('change', 'tfoot select', function (event) {
      //use "colindex" attribute value to search corresponding column for selected option value
      dataTable.column($(event.target).attr('colindex')).search($(event.target).val()).draw();
    })
<link href="//cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>

<table id="example">
</table>

2 个答案:

答案 0 :(得分:1)

您可以使用.appendTo( $(column.header()).empty() )替换列标题的内容。您还可以在initComplete回调中添加事件监听器,并将其直接附加到输入。

const dataSet = [
  ["Tiger Nixon", "System Architect", "Edinburgh", "5421", "2011/04/25", "$320,800"],
  ["Garrett Winters", "Accountant", "Tokyo", "8422", "2011/07/25", "$170,750"],
  ["Lorem ipsum", "Accountant", "Edinburgh", "1562", "2011/07/25", "$86,000"],
  ["Ashton Cox", "Junior Technical Author", "San Francisco", "1562", "2009/01/12", "$86,000"],
];

const dataTable = $('#example').DataTable({
  data: dataSet,
  dom: 't',
  columns: ['Name', 'Job Title', 'Location', 'Id', 'Hire Date', 'Salary'].map(header => ({
    title: header
  })),
  initComplete: function () {
    this.api().columns().every( function () {
      let column = this; 
      let select = $('<select><option value="">All</option></select>')
      .appendTo( $(column.header()).empty() )
      .on( 'change, click', function ( e ) {
        e.stopPropagation();
        let val = $.fn.dataTable.util.escapeRegex( $(this).val() );
        column.search( val ? '^'+val+'$' : '', true, false ).draw();
      });
      column.data().unique().sort().each( function ( d, j ) {
        select.append( '<option value="'+d+'">'+d+'</option>' )
      });
    });
  }
});
<link href="//cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>

<table id="example">
</table>

答案 1 :(得分:1)

您可以使用自定义<select>节点替换默认column().header(),如下所示:

const dataSet = [
	["Tiger Nixon", "System Architect", "Edinburgh", "5421", "2011/04/25", "$320,800"],
	["Garrett Winters", "Accountant", "Tokyo", "8422", "2011/07/25", "$170,750"],
	["Ashton Cox", "Junior Technical Author", "San Francisco", "1562", "2009/01/12", "$86,000"],
];

const dataTable = $('#example').DataTable({
		data: dataSet,
		dom: 't',
    ordering: false,
		columns: ['Name', 'Job Title', 'Location', 'Id', 'Hire Date', 'Salary'].map(header => ({title: header})),
    initComplete: function(){
      const table = this.api();
      table.columns().every(function(){
        //grab initial column title
        const title = $(this.header()).text();
        //replace header with <select> node
        $(this.header()).html(`<select><option value="">${title} (All)</option></select>`);
        //grab unique sorted column values into <option> nodes
        const options = this.data().unique().sort().toArray().reduce((options, item) => options += `<option value="${item}">${item}</option>`, '');
        //population <select> with options
        $(this.header()).find('select').append(options);
      });
    }
});


//filter upon option select
$('#example').on('change', 'thead select', event => dataTable.column($(event.target).closest('th')).search($(event.target).val()).draw());
<!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>
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
</head>
<body>
  <table id="example"></table>
</body>
</html>

但这会影响排序功能-每次单击/选择选项时,列排序顺序都会互换(就像可以在此问题的另一个答案中看到的那样。可以将其禁用,因为这是在我的工作中完成的)如果仍然需要该功能,则有一种解决方法。