1

I was wondering if the rendering of the table after receiving an ajax response can be modified. This seems related to the render function described here: https://www.datatables.net/manual/orthogonal-data.

My server returns Data like

{
    "name":       
                       {
                        id: "123456",
                        value: "Tiger Nixon"
                        }
}

I want to add to each name cell the id of the name as data-attribute or as id for the td and want to add a .on( "click", handler ) for each cell.

Is this possible?

Thanks in advance

2 Answers 2

1

You can use DT_RowData or DT_RowAttr (requires DataTables 1.10.5 or higher) parameters in your returned data to assign attributes to <tr> element which you can later retrieve in click handler, see Server-side processing chapter in the manual.

Alternatively you can use render method but it may not be as effective. I assumed below that index of your name column is 0 and that you want to set data-id attribute.

var table = $('#example').DataTable({
   "columnDefs": [{
      "data": "name.value",
      "targets": 0,
      "render": function ( data, type, full, meta ) {
         if(type === 'display'){
            $('#example').DataTable().cell(meta.row, meta.col).nodes().to$().attr('data-id', full['name']['id']);
         }

         return data;
      }
   }]
});

You can add click event handler using the code below:

$(document).ready(function(){
    var table = $('#example').DataTable({
       // Define DataTables initialization options here 
    });

    $('#example tbody').on('click', 'td', function(){

       // Use table to access various API function
       //
       // For example:
       // var data_cell = table.cell(this).data();

    });
});
Sign up to request clarification or add additional context in comments.

Comments

0

This is possible by using the columns.createdCell function.

The answer of Gyrocode is correct for an old DataTables version.

1 Comment

According to the manual you're mentioning above createdCell can be used as a complement to columns.render. The code shown in my answer is for the latest DataTables version (1.10.x).

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.