I have a couple of applications which use jquery 3.2.1 and DataTables 1.10.15.
In the first application - which all works fine - I made a reference to a single DataTable as follows:
var myTable = $('#myTable').DataTable({ ... });
If I need to reference that DataTable it's easy because I can do this:
var row = myTable.row(tr);
In the second application there are multiple DataTables on one page. The way in which these were created is using $.each()
in jquery:
$.each($('table'), function () {
var dt_id = $(this).attr('id');
$('#' + dt_id).DataTable({ ... });
});
This targets each <table>
which is present in the HTML present on page load. It creates a variable called dt_id
which has the value of the ID of the <table>
. It then initialises the DataTable on it.
So if, for example, I have 3 tables:
<table id="tableA"> ... </table>
<table id="tableB"> ... </table>
<table id="tableC"> ... </table>
I end up with 3 DataTables being initialised on ID's #tableA
, #tableB
and #tableC
.
The problem I'm having is that outside the $.each()
I want to be able to refer to a specific DataTable when the user clicks on a particular row inside it. So if for example the user clicks a <tr>
inside #tableB
I need a variable which refers to that table.
I don't know the best way of creating these in my code? I've read JavaScript Dynamic Variable Names and one option would be to dynamically create a variable name, e.g.
$.each($('table'), function () {
var dt_id = $(this).attr('id');
var dynamicVar = $('#' + dt_id).DataTable({ ... });
});
But how do I create that dynamicVar
at this point?
Another option I thought of would be to read the ID of the table that the user has clicked (e.g. If the user clicks a <tr>
then find the ID of the parent <table>
, e.g. #tableB
). Not sure if that's viable and even if it is, how do you access .DataTable(...)
from that?