JAVASCRIPT   61

dynamic table init js

Guest on 15th July 2022 01:49:19 AM

  1. function fnFormatDetails ( oTable, nTr )
  2. {
  3.     var aData = oTable.fnGetData( nTr );
  4.     var sOut = '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">';
  5.     sOut += '<tr><td>Rendering engine:</td><td>'+aData[1]+' '+aData[4]+'</td></tr>';
  6.     sOut += '<tr><td>Link to source:</td><td>Could provide a link here</td></tr>';
  7.     sOut += '<tr><td>Extra info:</td><td>And any further details here (images etc)</td></tr>';
  8.     sOut += '</table>';
  9.  
  10.     return sOut;
  11. }
  12.  
  13. $(document).ready(function() {
  14.  
  15.     $('#dynamic-table').dataTable( {
  16.         "aaSorting": [[ 4, "desc" ]]
  17.     } );
  18.  
  19.     /*
  20.      * Insert a 'details' column to the table
  21.      */
  22.     var nCloneTh = document.createElement( 'th' );
  23.     var nCloneTd = document.createElement( 'td' );
  24.     nCloneTd.innerHTML = '<img src="images/details_open.png">';
  25.     nCloneTd.className = "center";
  26.  
  27.     $('#hidden-table-info thead tr').each( function () {
  28.         this.insertBefore( nCloneTh, this.childNodes[0] );
  29.     } );
  30.  
  31.     $('#hidden-table-info tbody tr').each( function () {
  32.         this.insertBefore(  nCloneTd.cloneNode( true ), this.childNodes[0] );
  33.     } );
  34.  
  35.     /*
  36.      * Initialse DataTables, with no sorting on the 'details' column
  37.      */
  38.     var oTable = $('#hidden-table-info').dataTable( {
  39.         "aoColumnDefs": [
  40.             { "bSortable": false, "aTargets": [ 0 ] }
  41.         ],
  42.         "aaSorting": [[1, 'asc']]
  43.     });
  44.  
  45.     /* Add event listener for opening and closing details
  46.      * Note that the indicator for showing which row is open is not controlled by DataTables,
  47.      * rather it is done here
  48.      */
  49.     $(document).on('click','#hidden-table-info tbody td img',function () {
  50.         var nTr = $(this).parents('tr')[0];
  51.         if ( oTable.fnIsOpen(nTr) )
  52.         {
  53.             /* This row is already open - close it */
  54.             this.src = "images/details_open.png";
  55.             oTable.fnClose( nTr );
  56.         }
  57.         else
  58.         {
  59.             /* Open this row */
  60.             this.src = "images/details_close.png";
  61.             oTable.fnOpen( nTr, fnFormatDetails(oTable, nTr), 'details' );
  62.         }
  63.     } );
  64. } );

Raw Paste


Login or Register to edit or fork this paste. It's free.