How to do an initial filter in DataTables

How to do an initial filter in DataTables

SamanthaTsangSamanthaTsang Posts: 12Questions: 4Answers: 0

Hello,
I would like to do an initial filter when the page is loaded. I tried the code below, but the searching word was shown in the search box and user can edit the searching word. How can I make it disappear and not allow user to change the initial filter? Thank you.

"search": {"search": "Samantha Tsang"}

This question has accepted answers - jump to:

Answers

  • rf1234rf1234 Posts: 2,810Questions: 85Answers: 406
    edited January 2023 Answer ✓

    One solution is to use a column filter. That will not use the global search field and won't influence its contents.

    table
        .on('init', function (e, settings, json) {
            table.columns("#yourColId").search("Samantha Tsang").draw().columns.adjust();
            // or: table.columns( [2] ).search("Samantha Tsang").draw().columns.adjust();
        })
    

    https://datatables.net/reference/api/columns().search()

  • SamanthaTsangSamanthaTsang Posts: 12Questions: 4Answers: 0

    How about if I would like to search on more than one column? Can I write something like this?

    table.columns( [2,4] ).search("Samantha Tsang").draw().columns.adjust();

  • allanallan Posts: 62,099Questions: 1Answers: 10,183 Site admin
    Answer ✓

    No - that would apply the filter "Samantha Tsang" to both columns 2 and 4 using AND logic, not OR (which I suspect is what you would want).

    You can also use searchCols to set the filtering during the table's initialisation.

    Stepping back a moment:

    How can I make it disappear and not allow user to change the initial filter?

    I assume the end user shouldn't be able to change the filter, nor should they even be aware of it? A more common example of this might be using a query parameter to perform filtering - e.g. list.php?category=2 and you'd filter by the category?

    Assuming that is the case, then you want to apply a WHERE filter on the server-side when getting the data to populate the table.

    Allan

  • SamanthaTsangSamanthaTsang Posts: 12Questions: 4Answers: 0

    Yes, you are right, I want to filter "Samantha Tsang" on either column 2 OR column 4. I tried searchCols before, but it can only provide the AND logic.

    Does it mean that only the backend WHERE filter can provide the OR logic? Thanks a lot.

  • allanallan Posts: 62,099Questions: 1Answers: 10,183 Site admin

    If you wanted to do it client-side and you are using client-side processing, then you could use a custom search plug-in. However, if you don't want the user to remove the filter, then yes, do it server-side.

    Allan

Sign In or Register to comment.