user2360062
user2360062

Reputation: 703

Inserting custom data attributes into jQuery DataTables

Problem:

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

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?

Upvotes: 15

Views: 17916

Answers (2)

Stucco
Stucco

Reputation: 420

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).

Upvotes: 4

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.

Upvotes: 19

Related Questions