Reputation: 6111
I am using the latest version of DataTables and I'm having difficulty searching my DataTable using a custom filter form. This is the code that I'm using:
$("#user-search").on("submit", function (e) {
e.preventDefault();
const firstName = $("#first-name").val();
const lastName = $("#last-name").val();
const email = $("#email").val();
const elevated = $("#elevated").is(":checked");
if (firstName.length > 0) {
grid.column("FirstName").search(firstName);
}
if (lastName.length > 0) {
grid.column("LastName").search(lastName);
}
if (email.length > 0) {
grid.column("Email").search(email);
}
grid.column("Elevated").search(elevated);
grid.draw();
});
If I set a break-point or a debugger on my first conditional statement and walk my way through the code it looks as if the code should execute as expected. However what is happening is that it never redraws my data.
What I mean is that I can enter values into my search form, click search, it call grid.column("...").search(...);
, get to grid.draw();
and the data that was visible before the search is still the same data that after the search.
Upvotes: 0
Views: 239
Reputation: 6111
After doing some digging around the API documentation, I was ultimately able to solve the issue.
The problem was two-fold. First, I was providing the wrong column selector. I had incorrectly assumed that passing the column's name as outlined in columns.data was how you selected the column. Instead, you need to specify the columns.name property and then in the columns selector you append the :name
suffix:
var grid = $("...").DataTable(
...
columns: [
...
{
data: "FirstName",
name: "FirstName",
title: "First Name"
}
...
]
);
and then:
grid.column("FirstName:name").search(firstName);
The second problem was that because I didn't want the search input that is provided whenever you initialize DataTables, I set the datatable.Searchable property to false. This prevented the search method from executing at all. Instead, I removed that property (because it is set to true by default) and then I set the datatable.Dom property:
var grid = $("...").DataTable(
...
dom: "ltipr"
);
Finally, something unrelated but may be usefult for those who arrive here via a Google/Bing search, my jQuery would not give me the desired behavior. If I searched for something, reset the form, and tried to search again, it would not redraw the datatable with all of the rows. For this, I simply removed my If/Then statements.
Upvotes: 1