Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add dropdown filter on jquery datatables plugin on single column?

I want to add a drop-down filter on dataTables, only on a single column. I have added the below code, but it add drop-downs on all columns:

$('#dataTables-example').DataTable({
    responsive: true,
    "pageLength": 100,
    "lengthMenu": [100, 250, 500, "All"],
    initComplete: function () {
        this.api().columns().every( function () {
        var column = this;
        $('#dataTables-example .head .head_hide').html('');

        var select = $('<select id="formfilter" class="filterdropdown"><option value="">'+$(column.header()).text()+'</option></select>')
            .appendTo( $(column.header()).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>' )
        });
    }); 
});
like image 278
Waseem Bashir Avatar asked Sep 16 '16 06:09

Waseem Bashir


1 Answers

SOLUTION

Change

this.api().columns().every( function () {

to

this.api().columns(1).every( function () {

where 1 is zero-based column index.

NOTES

  • To add filter to certain columns use columns([1,3]) format instead.
  • You need to disable sorting for that column, because everytime the filter is clicked your column would be sorted. Otherwise use multi-line header or add filter to footer instead.
like image 134
Gyrocode.com Avatar answered Sep 24 '22 16:09

Gyrocode.com