Search code examples
javascriptjquerydatatabledatatables

DataTable - Why can't I get individual column searching (select inputs) working?


I'm using a JavaScript table goodies-pack from DataTables.net and I've come across a feature that greatly fits to my need, the individual column searching (select inputs), found here.

This feature allows to drill-down on the column data, filtering it down.

I've tried the standard implementation with no luck. I find no specific field on the implementation and have tried removing all other properties.

My code is:

<script type="text/javascript">
    $(document).ready(function() {
        $('#alertLogTable').DataTable( {
            language: {
                url: '//cdn.datatables.net/plug-ins/1.10.11/i18n/Portuguese-Brasil.json'
            },
            responsive: true,
            initComplete: function () {
                this.api().columns().every( function () {
                    var column = this;
                    var select = $('<select><option value=""></option></select>')
                        .appendTo( $(column.footer()).empty() )
                        .on( 'change', function () {
                            var 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>' )
                } );
                } );
            }
        });
    });
</script>

The demo on the datatables.net page shows buttons beneath each column to filter it. I don't get those and the filtering feature. What am I missing here?


Solution

  • Your code works fine. I am 100% certain that you just have forgotten to include a <tfoot> section. The footer is not added by magic, if <tfoot> is not present your <select>'s is inserted to nothing. So remember :

    <table>
      <thead>
        <tr><th></th></tr>
      </thead>
      <tbody>
        <tr><td></td></tr>
      </tbody>
      <tfoot>
        <tr><th></th></tr>
      </tfoot>
    </table>