15

Problem:

  • I am using JQuery DataTables v1.10 for a work-related project.

  • The project requires a Datatable to be defined and created with parsed JSON data passed in as the values of the table

  • Once the datatable has been created, every cell in each column should have a click event that opens a pop in and pass in a list of names in JSON, received from an endpoint. The endpoint changes depending on which table cell is clicked.

  • I think, upon datatable instantiation, I need to store some sort of unique information in an HTML5 data-attribute defined on each table cell element. I was hoping to declare a custom data-attribute (ex: data-endpoint = "endpoint id") but I'm not Sure if that is possible to do if the table rows are being dynamically generated via DataTables.

Because I don't know/understand what my options are, I'd like to describe what I ideally would like to do:

  • Instantiate a datatable and pass it the parsed JSON data.
  • On table instantiation, set a custom data-attribute on each table cell element.
  • Access the table cell click event, pass it the information stored in the correct data-attribute, in order to get the correct endpoint.
  • Create a popin that will display the results received from the endpoint.

The part I don't understand is how to create a custom data-attribute on the table cell element. Is this possible or do I need to think of another approach?

2 Answers 2

19

You can try with the createdRow callback on instantiation. Example:

$table.dataTable({

    "destroy": true, // To replace existing data
    "data": jsonData,
    "columns": columns,

    // Per-row function to iterate cells
    "createdRow": function (row, data, rowIndex) {
        // Per-cell function to do whatever needed with cells
        $.each($('td', row), function (colIndex) {
            // For example, adding data-* attributes to the cell
            $(this).attr('data-foo', "bar");
        });
    }
});

I think this can help you to do what you need.

4

I had to do something kind of like that. I'm not sure about the rest, but I used the columnDefs option to set the attributes.

....
"destroy": true, // To replace existing data
"data": jsonData,
"columns": columns,
// Sets the attribute
"columnDefs": [{
    "targets":'_all',
    "createdCell": function(td){
        td.setAttribute('foo','bar');
    }
}]
...

It still uses the createdCell option, but it mimics what I found in their documentation (https://datatables.net/reference/option/columns.createdCell).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.