0

I have added a searchbox to the header of my table generated by the Datatables plugin. It places a searchbox above every column in the header. I need the search filter to be applied to only a few columns. Lets say column 0 and 6 need a search filter the others not. Is there a way to do this? I cant find a answer anywhere on how to make this happen and I am new to coding so I have not yet found a way to make this happen. Below code I use to create the search header.

$('#OBTable thead tr')
        .clone(true)
        .addClass('filters')
        .appendTo('#OBTable thead');
                
                var table = $('#OBTable').dataTable({
                
                 "ajax": {
                    "url": "SelectData.php",
                    "dataSrc": "data",
                },
                 orderCellsTop: true,
                 select: true,
                   initComplete: function () {
            var api = this.api();
 
            // For each column
            api
                .columns()
                .eq(0)
                .each(function (colIdx) {
                    // Set the header cell to contain the input element
                    var cell = $('.filters th').eq(
                        $(api.column(colIdx).header()).index()
                    );
                    var title = $(cell).text();
                    $(cell).html('<input type="text" placeholder="' + title + '" />');
 
                    // On every keypress in this input
                    $(
                        'input',
                        $('.filters th').eq($(api.column(colIdx).header()).index())
                    )
                        .off('keyup change')
                        .on('keyup change', function (e) {
                            e.stopPropagation();
 
                            // Get the search value
                            $(this).attr('title', $(this).val());
                            var regexr = '({search})'; //$(this).parents('th').find('select').val();
 
                            var cursorPosition = this.selectionStart;
                            // Search the column for that value
                            api
                                .column(colIdx)
                                .search(
                                    this.value != ''
                                        ? regexr.replace('{search}', '(((' + this.value + ')))')
                                        : '',
                                    this.value != '',
                                    this.value == ''
                                )
                                .draw();
 
                            $(this)
                                .focus()[0]
                                .setSelectionRange(cursorPosition, cursorPosition);
                        });
                });
        },
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Martin4523
  • 107
  • 10

1 Answers1

1

The DataTables columns() API function can be given a column selector. This can take various forms. One option is to provide an array containing the indexes of the columns you want to contain a search filter.

So, for example you can specify:

.columns( [0, 6] )

I recommend you also look at the approaches in the following official examples:

You should also remove the eq(0) call - I don't believe that is a valid DataTables API function here.

As you can see from the documentation there are other options you can also use - such as providing a class name in the relevant heading cells - but an array of indexes is probably the simplest approach.


Update

The follow-up question is:

now the rest of the columns contain the name of the column header.. Is there a way to leave those empty?

You have not shown us what your HTML table looks like, so this is a guess, based on the assumption that you start with one heading row... I think this is a reasonable assumption...

If you want to avoid having repeated column headings, then you need to clear the contents of the cloned heading row, after you have performed the colone().

One way to do this is as follows:

$('#OBTable thead tr:eq(1) th').text("");

This means the cloned row will start out with no values in any of the heading cells.

This needs to be added after your command which performs the clone operation, and before you create the DataTable.

andrewJames
  • 19,570
  • 8
  • 19
  • 51
  • Thanks for your reaction, that seems to work. But now the rest of the colomns contain the name of the colomn header.. Is there a way to leave those empty? – Martin4523 Oct 16 '21 at 22:44
  • Perhaps a way to use this line .addClass('filters') to only the colomns 0 and 6 would solve the complete question? But i dont know how to add that class to only the 0 and 6 th element.. – Martin4523 Oct 16 '21 at 22:47
  • If I have understood your comment correctly, you can use another jQuery command to clear each of the cloned heading cells, before you configure the DataTable, I have updated the answer. – andrewJames Oct 17 '21 at 00:04
  • Added the code as folowed: $('#OBTable thead tr') .clone(true) .addClass('filters') .appendTo('#OBTable thead'); $('#OBTable thead tr:eq(1) th').text(""); This removes the option to add a title in the placeholder. But I can live with that. Thanks ! – Martin4523 Oct 17 '21 at 00:33
  • My next follow up question would be how to make sure that only the exact values are found. So when I search Anneke the result is Anneke and not as it is now Janneke is also showed. – Martin4523 Oct 17 '21 at 00:34
  • A new, different question should be asked as _A New Question_. But in this case, I think you will find that your new question has been asked and answered on Stack Overflow several times already. You can do some research for yourself. As an example, I performed a Google search which led me to several answers, including this: [DataTables column search for exact match](https://stackoverflow.com/questions/44003585/datatables-column-search-for-exact-match). So, please do some research, try to use the answers you find - and if you are still stuck, then you can write a new question. Good luck! – andrewJames Oct 17 '21 at 01:23
  • Thanks for your reaction. I did do that research found a lot of regex questions. But I cant figur out how to implent that regex into the above example – Martin4523 Oct 17 '21 at 08:03
  • Understood. If you ask this as a new question, be sure to show what research you have already done, so people will not spend time repeating that research. Also be sure to show what you actually tried, based on your research (show the specific code attempts) and also describe what happened when you ran the code. You can also take a look at [ask] for more general guidance. I am sure someone will be able to help you. – andrewJames Oct 17 '21 at 13:57
  • Hey thanks again. I have asked a new question see the folowing link. I will try to save my attempts next time as I mostly remove and search further untill i get stuck as I do now.. https://stackoverflow.com/questions/69602700/datatables-search-exact-match-on-header-search-column?noredirect=1#comment123026233_69602700 – Martin4523 Oct 17 '21 at 14:52