I'm using DataTables and added a listener for the search.dt
event with the intention of showing a loading message while the search is performed followed by removing that message (or showing a search completed message while testing) once draw.dt
is called.
I'm logging messages successfully to the console for each event respectively, but for some reason only on draw.dt
am I able to update the DOM successfully to show a message. I've used the same code in search.dt
but I don't see any change to the HTML I'm trying to modify to display my loading message. See below.
let table = $('#product-table').on( 'search.dt', function () {
$('#form-feedback').html('Searching...'); // this DOESN'T WORK
console.log('searching...'); // this works
} ).on( 'draw.dt', function () {
$('#form-feedback').html('Done.'); // this works
console.log('done searching.'); // this works
} ).DataTable({
"lengthMenu": [10,20,25,50,100],
"pageLength": 25,
"order": [[ 7, "desc" ]],
"stripeClasses":["even","odd"],
"responsive": true,
"dom": 'lrtip',
"columnDefs": [
{ "visible": false, "targets": [4,5,6,7] }
]
});
The console is logging my searching...
message whenever a new search runs, but doesn't display the actual message on the page per the HTML I'm trying to update. However, on completion of the search the page DOES display my Done message.
What should I be checking to troubleshoot the cause of this? Has anyone had this issue? Thanks.
I ended up using a debounce on the search and seemed to get this working by displaying my searching...
message inside the debounce function. I'm guessing the issue had to do with the search.dt
event immediately triggering a redraw of the table or other event. I used Lodash debounce and the below solution gave me what I was looking for. Maybe this will be useful for someone else if they go a similar route.
var query = undefined;
// when search input changes...
$('#search-input').keyup( function () {
// if there's been no change to the field then do nothing
if (query === this.value) {
return;
}
// update with the value entered
query = this.value;
/* Wait until at least 2 characters have been entered, or user has cleared the input */
if (this.value.length >= 2 || (!this.value)) {
// run our debounce search function
debouncedSearchDraw(query);
}
} );
// the debounce search function
var debouncedSearchDraw = debounce(function(val) {
// successfully display searching message to user
$('#form-feedback').html('Searching...');
// search and redraw the table with the results
table.search(val).draw();
// after drawing the table remove the searching message
$('#form-feedback').html('');
}, 750);