Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add html element within td after Ajax request in jQuery DataTables

I want to add html element within td after get response from ajax.

Result will be somethings like:

<tr>
<td class="mycus-class" data-title="abc"><span class="mycus-class2">XYZ</span></td>
<td class="mycus-class" data-title="ghi"><span class="mycus-class2">GKL</span></td>
.....
</tr>
like image 536
vineet Avatar asked Oct 07 '15 13:10

vineet


People also ask

How append ajax response to Datatable?

var dataTable = $("#viewTable"). DataTable(); Then on ajax success, use dataTable. add([" "," ", " "]).

What are HTML DataTables?

DataTables is a powerful jQuery plugin which can be used to create HTML tables with functionality like searching, sorting and pagination. It can use almost any data source like DOM, Ajax, and server-side processing. It is mobile friendly library which can adapt to the viewport size.

What is Datatable in ajax?

DataTables has the ability to read data from virtually any JSON data source that can be obtained by Ajax. This can be done, in its most simple form, by setting the ajax option to the address of the JSON data source.


2 Answers

Very easy with a render() function, here a little demo :

var data = [
    { firstName: 'john', lastName : 'doe' }
]

var table = $('#example').DataTable({
    data : data,
    columns : [
       {  data : 'firstName',
          render : function(data, type, row) {
              return '<span class="mycus-class2">'+data+'</span>'
          }    
       },
       {  data : 'lastName' }
   ]        
})  

http://jsfiddle.net/e9be48oq/


You can target multiple columns in one call :

columnDefs : [
   { targets : [0,3,4,5],
     render : function(data, type, row) {
        return '<span class="mycus-class2">'+data+'</span>'
     }     
   }
]
like image 182
davidkonrad Avatar answered Nov 23 '22 14:11

davidkonrad


  "fnRowCallback": function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
                console.log(aData[1]);
                if (aData[1] == "Imported")
                {
                    // $('td').css('background-color', '#FBE9E7');
                     $(nRow).find('td:eq(1)').addClass('label label-success');
                } else if (aData[1] == "Inactive") {
                    $(nRow).find('td:eq(1)').addClass('label label-danger');
                } else if(aData[1] == "Exported") {
                   $(nRow).find('td:eq(1)').addClass('label label-primary');
                }else{
                  $(nRow).find('td:eq(1)').html('<span class="label label-default">'+aData[1]+'</span>');
                    // $.addClass('label label-default');
                }

            },
like image 44
Tarun Sharma Avatar answered Nov 23 '22 14:11

Tarun Sharma