hweiu321
hweiu321

Reputation: 123

Datatables <thead> dropdown filter not working

I'm putting the dropdown filter in <thead></thead>. But it can't function properly. The search filter in my website works perfectly but not the dropdown filter. I even checked the html code for <option><select> compared to the example in here. When I select one <option>, the table recognizes it as unmatched value, all rows missing.

Here's a screenshot of the table together with html inspector:

enter image description here

Here is my <select> dropdown html code:

<option value=""></option>
<option value="SK Ambong">SK Ambong</option>
<option value="SK Dudar">SK Dudar</option>
<option value="SK Kitou">SK Kitou</option>

Here's my JS code:

$('table').DataTable({
    ordering: false,
    initComplete: function () {
        const nonSearchableColNo = [1, 6, 7, 8];
        var api = this.api();

        // For dropdown column
        api.columns(2).every( function () {
            var column = this;
            var select = $('<select><option value=""></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 ( data, j ) {
                optionVal = data.match(/SK [A-Z]\w+/g);
                select.append( '<option value="'+optionVal+'">'+optionVal+'</option>' )
            } );
        } );
    }
});

Upvotes: 0

Views: 1111

Answers (1)

fdomn-m
fdomn-m

Reputation: 28611

The datatables.net documentation (and your code) matches on the full string, so that would be "SK Dudar 1", but you're getting SK+[word], eg "SK Dudar" (as also shown in your <option>).

"^SK Dudar$" does not match with "SK Dudar 1" so you get no matches.

Change

optionVal = data.match(/SK [A-Z]\w+/g);

to

optionVal = data;

to check the rest works, but may not work with what looks like an additional image (no html/datatables data provided, so can't be sure)

Or change

column.search(val ? '^'+val+'$' :...

to

column.search(val ? '^'+val : ''...

(ie remove the $)

Depending on what else is in that data column, you may need to change your search regex, eg

column.search(val ? '^'+val+'\s.?\w' : ''...

should also match "SK Dudar" to "SK Dudar 1", but not "SK Dudar 1 2".

You may need to move the image into a different column if it's not working, but it's not matching on HTML, rather on the column.search API of datatables.

Upvotes: 1

Related Questions