MDB Datatable: remove duplicative row clicks
I’m using MDBootstrap Datatable , with a clickable row:
Using Ajax, the table could be re-drawn, so I clear out the contents of the table (as to avoid it re-appending onto it). This is done on Row 4.
The JavaScript code that detects a row click is on Rows 16–21.
I realized that when the table is refreshed (with Ajax), while the number of rows are correct (no duplicates), the onClick function is called twice. And if the table was refreshed again, it would be called three times.
I needed to remove the EventListener from my element.
Solution 1 (Failure) — Use “removeEventListener”
My first thought was to “undo” the addEventListener() function.
I found there’s a removeEventListener() function . It takes minimum two parameters: type and listener.
I found this code that shows all event listeners on the page:
Running it in the Chrome Web Developer Console, I could at least see the type was “onclick”
I tried a few things for the listener but kept getting an error (specifically that I wasn’t passing in an Object).
Final Solution
I ended up removing the mdb-datatable element, and re-adding it:
I replaced the existing HTML element with a marker to serve as where I’ll dynamically place the DIV with the data table (notice it’s called the same, with the word “Position” appended on).
My JavaScript will remove the element and then place the data table after the position / marker:
Here, I’m using jQuery to append the element (Row 9)
I no longer need to run table.innerHTML = ‘ ’ since the table will be recreated
One thing left: this table is occasionally re-drawn. Upon page load, the data table isn’t there, so you’ll get an error on Row 4 above. Just check for its existence first (Rows 9–13 below).