Update the searchData before search.

Update the searchData before search.

LeuteciaLeutecia Posts: 3Questions: 1Answers: 0
edited March 2023 in Free community support

table.columns(0).search($("#searchInput").val()).draw();

Using this code to search, but actually, I need to remove the numbers from that column. How can I achieve that?

I saw this code for extending the search:

        $.fn.dataTable.ext.search.push(
            function( settings, searchData, index, rowData, counter ) {
                console.log('searchData', searchData[0])
                searchData = searchData[0].replace(/[0-9]/g, '');

                return true;
            }
        );

It doesn't work. I just need to update that searchData text.

Answers

  • kthorngrenkthorngren Posts: 20,370Questions: 26Answers: 4,779

    You could use orthogonal data to remove the numbers for the filter operation. Then you wouldn't need to use a search plugin.

    The search plugin is meant to perform comparisons, which you don't have. See this example. It gets the input value then performs a comparison with the data. Just use draw() to have the plugin execute. If you want to use the search plugin do something like this:

    $.fn.dataTable.ext.search.push(
        function( settings, searchData, index, rowData, counter ) {
            var val = $("#searchInput").val();
            console.log('searchData', searchData[0])
            myData = searchData[0].replace(/[0-9]/g, '');
    
            if (val === '') {
                return true;
            }
    
            if (myData === val) {
                return true;
     
            return false;
        }
    );
    

    Use table.draw() to execute the search plugin.

    Kevin

  • LeuteciaLeutecia Posts: 3Questions: 1Answers: 0

    Thanks for your answer.
    Sadly, It's not working.
    I don't understand your solution, myData will never be equal to val, so no search will be performed.
    Could you please explain how I could solve this using the orthogonal data with an example?

  • LeuteciaLeutecia Posts: 3Questions: 1Answers: 0
    edited March 2023

    Hey @kthorngren

    The orthogonal way worked like a charm. Didn't know this even existed. Massive thanks to you.

    Here's how I fixed it. In my columns array:

    {
        data: 'name',
        name: 'name',
        searchable:true,
        render: function ( data, type, row ) {
            switch (type) {
                case 'display':
                    return '<span>' + row.name + '</span><span>' + row.id + '</span>';
                default:
                    return row.name;
            }
        }
    },
    

    Edited by Allan - Syntax highlighting. Details on how to highlight code using markdown can be found in this guide.

Sign In or Register to comment.