Skip to content
Advertisement

Multiple Tables on Datatables with different option

I have multiple table (tbUser, tbRole, tbJob) and i want to make my code simple.

this is what i done before:

var userTable = $('#tbUser').DataTable();
var roleTable = $('#tbRole').DataTable();
var jobTable = $('#tbJob').DataTable();

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:

$('#tbUser tbody').on('click', '#btn_edit', function (e) {
  let index = $(this).parents('tr');
  let data = userTable.row(index).data();

  /** Something */
});

/** REPEAT EACH TABLE */

and I’ve tried :

$('table tbody').on('click', '#btn_edit', function (e) {
  let index = $(this).parents('tr');
  let data = userTable.row(index).data(); //===> But how to change table dynamicly on this line

  /** Something */
});

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.

const tables = {
    tbUser: userTable,
    tbRole: roleTable,
    tbJob: jobTable
}

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

$('table tbody').on('click', '.btn_edit', function (e) {
    const tableId = this.closest('table').id;
    const datatable = tables[tableId];

    const index = $(this).parents('tr');
    const data = datatable.row(index).data();

    /** Something */
});
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement