How to set a default search value for column using dropdown list example.

How to set a default search value for column using dropdown list example.

CJeromeACJeromeA Posts: 1Questions: 1Answers: 0

In the example for "Individual column searching (select inputs)" ( https://datatables.net/examples/api/multi_filter_select.html ), how would I have the Initialization ("initComplete") select a value so that the datatable was pre-"searched" on that value?

E.g.: Say that I want the datatable to always load up showing a "Position" of "Accountant", so then the 2 rows for "Accountant" are shown. Then I could select other options in Position or any of the other select dropdowns.

I tried setting the search.search option but then it only loads Accountant's. I tried removing the blank "option" from the example, and that shows the "Accountant" value in the dropdown but the datatable is not filtered until a "change" event fires on the select, so I tried to force ($...trigger("change")) the event, but that seemed to have no effect. Any help or advice will be greatly appreciated!

Thanks,
Jerome

Answers

  • ssathishkumarssathishkumar Posts: 1Questions: 0Answers: 0

    I'm also waiting a solution for this same scenario. following

  • 3dsanity3dsanity Posts: 1Questions: 0Answers: 0

    I found a work around that worked for us. I just reused the column.search() function once the table was ready. Hope this helps

    var lastCat = 'the category';
    var table = $('#Products').DataTable({
        "iDisplayLength": 40,
        initComplete: function () {
            this.api().columns('3').every( function () {
                var column = this;
                var select = $('<select><option value="">All Categories</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 ) {
                    if(lastCat === d) {
                        select.append( '<option SELECTED value="'+d+'">'+d+'</option>' )
                    } else {
                        select.append( '<option value="'+d+'">'+d+'</option>' )
                    }
                } );
                $(table).ready(function() {
            column.search( lastCat ? '^'+lastCat+'$' : '', true, false ).draw();
            });
            } );
        }
    });
    
This discussion has been closed.