javascriptjquerydatatabletablefilter

Using DataTable().search() with if statement


I have a problem with Datatable().search() function. What I'm hoping to achive is that when I type something starting with "x:" then I want to filter column with index 1, in other case it should filter column 0.

I haven't found any problems similar to mine. Maybe such operation is not possible with DataTable()?

Thanks for your time!

Here is my js code:

     function filterName() {

                    var regularExpression = $('.column_filter').val();
                    var columnNum = 0;

                    if (regularExpression[0] == 'x' && regularExpression[1] == ':') {
                        columnNum = 1;
                        regularExpression = regularExpression.substring(3, regularExpression);
                    } else {
                        columnNum = 0;
                    }

                    if (regularExpression[regularExpression.length - 1] == ' ') {
                        regularExpression = regularExpression.substring(0, regularExpression.length - 1);
                    }
                    regularExpression = regularExpression.replace(/\s/g, "|");

                    $('#table')
                        .DataTable()
                        .column(columnNum)
                        .search(
                            regularExpression,
                            true,
                            false
                        )
                        .draw();
                }

             $('#table')
                        .DataTable({
                            "paging": false,
                            "ordering": false,
                            "info": false,
                            "autoWidth": false,
                            "sDom": '<"top"i>rtlp'

                        });
                    $('.column_filter')
                        .on('keyup click',
                            function () {
                                filterName();
                            });

Solution

  • Ok, I found a solution. I had to clear search function.

    I added:

       $('#table')
                  .DataTable()
                  .columns()
                  .search('');
    

    before:

             $('#table')
                        .DataTable()
                        .column(columnNum)
                        .search(
                            regularExpression,
                            true,
                            false
                        )
                        .draw();