Utilize Datatables to apply filters dynamically

For displaying a list loaded via an AJAX call to the server, I utilized the datatables jQuery plugin. To integrate the search input inside my sidebar, I made use of the bFilter property to hide the filter.

$(function () {
    var generatedCustomerTable = $('#ItemsTable').DataTable({
        "order": [[0, "desc"]],
        "bSort": true,
        processing: true,
        serverSide: true,
        ajax: {
            url: "/api/Ajax/Test",
            method: "POST",
        },
        columns: [
            { visible: false, data: "id" },
            { orderable: false, data: "name" },
            { orderable: false, data: "value" },
        ],
        bLengthChange: false,       // Hide the page size
        bFilter: false,             // Hide the search box
        ordering: true,
        paging: true,
        pagingType: "full_numbers",
        pageLength: 10,
        language: {
            paginate: {
                first: '«',
                previous: '‹',
                next: '›',
                last: '»'
            },
            aria: {
                paginate: {
                    first: 'First',
                    previous: 'Previous',
                    next: 'Next',
                    last: 'Last'
                }
            }
        }
    });

    $("#btnTest").click(function () {
        // I WANT HERE TO SET THE FILTER
        generatedCustomerTable.draw();
    });
});

Although I want to programmatically set the filter text, I haven't found a way to do so yet.

Is there a function available that will enable me to set the filter value and subsequently call the .draw() method for refreshing the list contents?

Answer №1

When you adjust the bFilter setting to false in your code, not only does it hide the search box, but it also disables the search function in the dataTable.

To create a custom search box of your own, you need to enable the bFilter and then either hide the default search control with CSS (recommended) by using this code:

.dataTables_filter {
    display:none;
}

Or you can design your own table rendering using sDom | other link

Refer to the snippet below:

var dataSet = [
    [ 1, "Name 1","one" ],
    [ 2, "BRimos", "JS" ],
    [ 3, "pitaridis","Data" ],
    [ 4, "Stack", "overflow" ],
    [ 5, "Name 2","two" ],
    [ 6, "Name 3","three" ],
    [ 7, "Name 4","one" ],
    [ 8, "BRimos 2", "JS" ],
    [ 9, "pitaridis 2","Data" ],
    [ 10, "Stack 2", "overflow" ],
    [ 11, "Name 5","two" ],
    [ 12, "Name 6","three" ]
  ];
$(function () {
    var generatedCustomerTable =$('#ItemsTable').DataTable( {
        "order": [[0, "desc"]],
        "bSort": true,
        data: dataSet,
        columns: [
            {  visible: false,title: "id" },
            {  orderable: false,title: "name" },
            {  orderable: false,title: "value" }
        ],
        bLengthChange: false,       // Hide the page size
        bFilter: true,             // Hide the search box
        ordering: true,
        paging: true,
        pagingType: "full_numbers",
        pageLength: 5,
        language: {
            paginate: {
                first: '«',
                previous: '‹',
                next: '›',
                last: '»'
            },
            aria: {
                paginate: {
                    first: 'First',
                    previous: 'Previous',
                    next: 'Next',
                    last: 'Last'
                }
            }
        }
        
    } );

    $("#btnTest").click(function () {
       console.log($("#filter").val(),generatedCustomerTable);
        generatedCustomerTable
        .search($("#filter").val()).draw();
    });
});
.dataTables_filter {
  display:none;
}
<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<input id="filter" type="text" />
<button id="btnTest">search</button>

<table id="ItemsTable" width="100%"></table>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The automatic redirection feature on a webpage is not functioning correctly on mobile devices

There's a peculiar issue on our website that I'll do my best to explain, and I'll provide photo links for more clarity. In our WooCommerce site, the process of paying for the cart goes as follows: Click "place order" button pic: Page for o ...

Customizing the appearance of all Angular components with styles.scss

Is there a way to create a universal style in styles.scss that can be applied to all Component selectors (e.g. app-componentA, app-componentB ...)? I understand that I could manually add the style to each selector, but I am concerned that it may be forgot ...

Searching for values in nested arrays using lodash.find

Presented below is an array where I aim to employ lodash for item search: [ { "itemA": "apple", "itemB": [ { "itemC": "1", "itemD": "red apple" }, { "itemC": "2", "itemD": "green apple" }, ...

Tips for creating a multi-tenant application using Node.js (express.js)

I need help finding information on developing a multi-tenant application using Node.js. Can anyone offer some guidance? Thank you. My technology stack includes: Node.js Express.js Mocha.js Postgres SQL JavaScript HTML5 ...

Enhancing Highcharts: Extending Tooltip Functionality

My dataset contains a collection of data points that I want to display in a Highcharts chart. Here is an example of how the data looks: mydataset = [{ x: 1, y: 3, names: ["John", "Jane"] }, { x: 2, y: 4, names: ["Alice", "Bob"] }] ...

Difficulty in arranging DIVs on a flat surface

As a user running Win XP with Firefox, IE, and Google Chrome browsers, I'm encountering an issue where I can't seem to align two DIVs on the same horizontal plane. My goal is to have the left div occupy 24% of the screen width while the right div ...

Can WebSocket messages be encoded?

Is there a way to encrypt or obscure the data I transmit via websockets? For example, the message looks like this: var encryptedMsg = { type: "message", data: { message: "Hello world!" } } I require the ability to send this message in ...

Exploring the Power of BufferGeometry and Textures in Three.js

I am experiencing an issue where the texture does not show up when I try to load textures on a THREE.BufferGeometry. However, the texture displays correctly when using normal geometry. Could it be that textures are unsupported with BufferGeometry, or am I ...

Angular implementation of checkboxes to streamline data filtering

I am currently displaying FreeEvents using a checkbox and passing the value to the filter as filter:filterFreeEvent, which is working perfectly fine. However, I would like to avoid passing the value in the filter and instead use a change event of a checkb ...

Anchor tag buttons do not affect the font color and variables remain unchanged

I've been struggling to change the font color and background color of the <a> element, but nothing seems to work. I've attempted using hexadecimal notation and styling the .btn class without pseudo-classes, with no luck. Check out my CodeP ...

The issue of HTML5 Audio not playing after injecting the src URL

When the page loads, I have something similar to this: echo "<td class='audio'><audio controls><source src></audio></td>"; After that, I initiate an ajax call triggered by a click event to retrieve relative audio U ...

Move information from one webpage to a different page

After developing a site using NextJs, I successfully integrated Discord login functionality and was able to retrieve the user's guilds in the oauth file. Now, I am looking to send this list of guilds (in JSON format) to my dashboard page. In the oau ...

JSX/CSS: the text on the button is positioned outside of the button in Chrome browser

As I work on styling a React component using CSS, I noticed that I'm getting different results in Chrome and Firefox: Firefox (which is the desired behavior for both): https://i.sstatic.net/Q0LSD.png Chrome: https://i.sstatic.net/s2MWJ.png While I& ...

What is the best way to ensure a consistent spacing between two flex items?

I am working on a project to enhance my knowledge by rebuilding Facebook. One of the new concepts I am learning is Flexbox. When you resize the login page of Facebook, you'll notice that the Navigation shrinks but the logo and login inputs remain sta ...

"When you click on an Instagram link, it will now open within the app's browser rather

Is there a way to open a link from my profile in an external browser instead of the in-app browser on iOS or Android? Can I detect if a user is on a mobile device and open the link in a native browser on my own site using JavaScript? The problem arises wh ...

Steps for modifying the look of a button to display an arrow upon being clicked with CSS

Looking to enhance the visual appearance of a button by having an arrow emerge from it upon clicking, all done through CSS. Currently developing a React application utilizing TypeScript. Upon clicking the next button, the arrow should transition from the ...

Mastering sorting in AngularJS: ascending or descending, the choice is yours!

I have set up a table view with infinite scroll functionality. The table contains 2000 objects, but only shows 25 at a time. As the user scrolls to the bottom, it loads an additional 25 elements and so on. There is a "V" or "^" button in the header that sh ...

Delete the CSS class if the element with the class ".dropdown" does not currently have the class

In a larger view port, this menu is displayed horizontally. When you click on the dropdown, the menu expands and the list is shown in line. A span is added to show a list strip under the parent level. Everything seems to be working fine except for one thin ...

What could be the reason for this Javascript code not functioning as intended, failing to generate a random number between 1 and 3 when I click on any of the buttons

Could someone help me with generating a random number between 1 and 3 each time I click on one of the buttons (rock, paper, scissors)? I am new to programming and not sure what I'm doing wrong. <!doctype html> <html lang="en"> <head& ...

How to locate the position of an element within a multi-dimensional array using TypeScript

My data structure is an array that looks like this: const myArray: number[][] = [[1,2,3],[4,5,6]] I am trying to find the index of a specific element within this multidimensional array. Typically with a 1D array, I would use [1,2,3].indexOf(1) which would ...