I have multiple table (tbUser, tbRole, tbJob) and i want to make my code simple.
this is what i done before:
JavaScript
x
4
1
var userTable = $('#tbUser').DataTable();
2
var roleTable = $('#tbRole').DataTable();
3
var jobTable = $('#tbJob').DataTable();
4
Each tables has different options, columns and have one thing in common has column [action] to put View/Edit/Remove button. Is there a simple way to do jquery event click action button in each table.
This is my code:
JavaScript
1
9
1
$('#tbUser tbody').on('click', '#btn_edit', function (e) {
2
let index = $(this).parents('tr');
3
let data = userTable.row(index).data();
4
5
/** Something */
6
});
7
8
/** REPEAT EACH TABLE */
9
and I’ve tried :
JavaScript
1
7
1
$('table tbody').on('click', '#btn_edit', function (e) {
2
let index = $(this).parents('tr');
3
let data = userTable.row(index).data(); //===> But how to change table dynamicly on this line
4
5
/** Something */
6
});
7
Advertisement
Answer
Firstly your edit button needs to be targetted using a class not an ID, otherwise it will only ever find the first button.
Create an object that holds a reference to each of your tables. I’m using the table id as the key, and the instantiated datatable as the value.
JavaScript
1
6
1
const tables = {
2
tbUser: userTable,
3
tbRole: roleTable,
4
tbJob: jobTable
5
}
6
Then with your button click, identify which table it is part of and use that to grab the table instantiation from the object you created earlier
JavaScript
1
10
10
1
$('table tbody').on('click', '.btn_edit', function (e) {
2
const tableId = this.closest('table').id;
3
const datatable = tables[tableId];
4
5
const index = $(this).parents('tr');
6
const data = datatable.row(index).data();
7
8
/** Something */
9
});
10