Individual column searching filter for js sourced data using DataTable.js with filter at the top

痞子三分冷 提交于 2021-02-19 06:45:28

问题


I am unable to place the filter selects at the top. How do I achive?

I stuck to initComplete option as it is triggered just once upon DataTable fully initialized and API methods can be called safely.

Also where exactly would I make the column drop down values unnique

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>

回答1:


You may replace default column().header() with your custom <select> node, like that:

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>

But it will affect sorting feature - you'll get column sorting order swapped each time you click/select option (like it can be seen in another answer to this question. Either it can be disabled, as it is done in mine. If that feature still needs to be functional, there's a workaround for that.




回答2:


You can replace the content of the column-headers by using .appendTo( $(column.header()).empty() ). You also can add the eventlisteners inside the initComplete-callback and attach them directly to the inputs.

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>


来源:https://stackoverflow.com/questions/56363379/individual-column-searching-filter-for-js-sourced-data-using-datatable-js-with-f

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