자주 사용하는 DATATABLE 스크립트 구문

Admin 2020.04.27 09:50 조회 수 : 10

자주 사용하는 DATATABLE 스크립트 구문이다.

개인적인 필요에 따라 복사, 붙여넣기 하기위해 정리해 보았다. ^^

datatable.jpg

 

 

<link rel="stylesheet" type="text/css" href="{{asset('vendors/css/datatables/datatables.min.css')}}">
<style type="text/css">
div.dt-button-background {background:unset;}
#frmProg .dt-btn{display:inline-block;position:relative;margin:0 1.5rem;font-weight:400;color:#727E8C;text-align:center;vertical-align:middle;user-select:none;font-size:1rem;line-height:1rem;border-radius:0.267rem;}
#frmProg div.dt-button-collection {width:auto;}
#frmProg div.dt-button-collection button.dt-button.ml-1{margin-left:0rem!important;}
#frmProg div.dt-buttons button.dt-button{background-color:#E6EAEE!important;}
#frmProg button.dt-button, #frmProg div.dt-button, a.dt-button{line-height:1.3em;margin-right:0em;margin-bottom:0em;padding:0.437rem 1.8rem;color:#475F7B;font-size:1rem;border:1px solid #e2e8f0;border-radius:0.267rem;background-image:unset;transition:color 0.15s ease-in-out,background-color 0.15s ease-in-out,border-color 0.15s ease-in-out,box-shadow 0.15s ease-in-out;}
#frmProg button.dt-button:not(:first-child) {margin-left:1.5rem!important;/*margin-top:0.467rem;*/}
#frmProg button.dt-button.btn-primary {border-color:#e2e8f0!important;background-color:#E6EAEE!important;color:#475F7B;}
#frmProg .btn-light-secondary:active, #frmProg .btn-light-secondary.active, #frmProg .btn-light-secondary:hover, #frmProg .btn-light-secondary.hover, #frmProg .card-header button.dt-button:hover, #frmProg button.dt-button:active {background-color:#E6EAEE!important;color:#475F7B!important;border-radius:0.267rem;}
#frmProg .btn {line-height:1.3rem;}
#frmProg .btn i {top:0px;margin-right:5px;}
div.dataTables_wrapper div.dataTables_processing {position:absolute;top:10%;left:50%;}
</style>

<form action="{{ route('program.index') }}" id="frmProg" method="GET">
  <input type="hidden" name="page" value="{{ request()->get('page') }}" />
  <div class="form-row align-items-center">
    <div class="col-3">
      <input class="form-control" type="search" name="search" placeholder="Search" @if(Request::get('search')) value="{{Request::get('search')}}" @endif>
    </div>
    <div class="col-auto">
      <div>
        <button class="btn btn-white border dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
          Filter Options
        </button>
        <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
          <input type="hidden" name="program" value="{{ Request::query('program') }}" />
          <button class="dropdown-item @if(Request::query('program')) dropdown-item-checked @endif" data-filter="program" type="button">NEW</button>
        </div>
        <a href="#" class="btn btn-light-secondary ml-1 mb-0 mailTo"><i class="bx bx-mail-send font-medium-1"></i>Email</a>
        <div class="dt-btn"></div>
      </div>
    </div>
    <div class="col">
      <a href="{{ route('program.index') }}" class="btn btn-light">Reset</a>
    </div>
  </div>
</form>
 
<table id="테이블" class="table table-striped table-hover flex-auto nowrap" style="width:100%;">
<thead>
    <tr>
      <th>ID</th>
      <th class="iCODE" style="width:80px;padding:0 20px;">Code</th>
      <th class="iNAME">Name</th>
      <th class="iKIDS">Kids</th>
      <th class="iSUM">Sum</th>
      <th class="iNOTE">Note</th>
    </tr>
</thead>
<tbody>
    @foreach ( $programs as $key => $prog)
    <tr class="iData">
      <td>{{$prog->id}}</td>
      <td><span>{{$prog->CODE}}</span></td>
      <td><a href="#" data-mail="{{ $prog->EMAIL }}"><span>{{$prog->NAME}}</span></a></td>
      <td>{{$prog->KIDS}}</td>
      <td>{{$prog->SUM}}</td>
      <td>{{$prog->NOTE}}</td>
    </tr>
    @endforeach
  </tbody>
  <tfoot>
    <tr>
      <th>ID</th>
      <th> </th>
      <th>TOTALS</th>
      <th><span> </span></th>
      <th>$ <span> </span></th>
      <th> </th>
    </tr>
</tfoot>
</table>
<div id="pageWarp">
<!--// 라라벨 페이징 사용시 -->
{{-- $programs->appends(Request::except(['_token']))->links() --}}
</div>

<script src="{{asset('vendors/js/datatables/datatables.min.js')}}"></script>
var csToken = $('meta[name="csrf-token"]').attr('content');
function clearTag ( t ) {
  return t.replace(/(<([^>]+)>)/ig,"");
}
$.ajaxSetup({
  headers: { 'X-CSRF-TOKEN': csToken }
});
$.extend( true, $.fn.dataTable.defaults, {
  buttons: [
    {
      extend: 'excel',//'excelHtml5'
      className: 'btn btn-light-secondary mb-0',
      text: '<i class="bx bx-file font-medium-1"></i>Export to Excel',
      exportOptions: {
        format: {
          header: function ( data, column, row ) {
            return data.replace( /<br\s*\/?>/ig, '\r\n' ); // LINE BREAK IN HEADER
          },
          body: function ( data, column, row ) {
            return (column === 2) ? data.replace( /\n/g, '"&CHAR(10)&CHAR(13)&"' ) : data.replace(/( |<([^>]+)>)/ig, ""); // REMOVE TAG IN BODY
          }
        }
      },
      customize: function( xlsx ) { // WRAP TEXT
        var sheet = xlsx.xl.worksheets['sheet1.xml'];
        $('row c', sheet).attr( 's', '55' );
      }
    },
    {
      extend: 'print',
      className: 'btn btn-light-secondary mb-0',
      text: '<i class="bx bx-printer font-medium-1"></i>Print',
      exportOptions: {
        stripHtml: false
      }
    }
  ],
  order: [ [1, 'asc'] ],
  autoWidth: true,
  searching: false,
  ordering: true,
  rowReorder: false, // do not change to true
  displayLength: 100,
  pageLength: 100,
  stateSave: false,
  lengthChange: false,
  serverSide: false, // 서버사이드인 경우 true
  //ajax: '{{ route("program.index") }}', // 서버사이드 AJAX 인 경우 url 입력
  info: false,
  paging: false, // DATATABLE이 제공하는 페이징을 사용할 경우 true
  processing: true,
  responsive: true // 반응형
} );

jQuery(document).ready(function($) {
  var tobcc = [], dtable = $('#테이블').DataTable({
    columns: [
      { data: 'id', name: 'id', className: '', orderable: true, visible: false }, // serverSide 인경우, data, name 에 출력할 db 컬럼 추가
      { className: 'iCODE', visible: true },
      { className: 'iNAME', orderable: true, visible: true },
      { className: 'iKIDS', orderable: true, visible: true },
      { className: 'iSUM', orderable: true, visible: true },
      { className: 'iRSA', orderable: true, visible: true, responsivePriority: 10001 }
    ],
    initComplete: function () {
      var api = this.api();
    },
    createdRow: function( row, data, dataIndex ) {
      var email = $( row ).find('.iNAME a').data('mail');
      if(email!=undefined) tobcc.push(email);
      $('.mailTo').attr('href', 'mailto:?bcc='+tobcc.join('; '));
    },
    footerCallback: function ( row, data, start, end, display ) {
      var api = this.api(), data;
      var intVal = function ( i ) {
        return typeof i === 'string' ? i.replace(/(<([^>]+)>|[\$,])/ig,"")*1 : typeof i === 'number' ? i : 0;
      };
      // ROW 자료 갯수
      var rowTotal = api.column( 1 ).data().filter(function (value, index) {
        return value !='' ? true : false;
      }).length;
      $( api.column( 1 ).footer() ).html( rowTotal );
      // 다중 컬럼 합계 예제
      api.columns('.iSUM, .iKIDS' ).every(function(i) {
        var elem = $(this);
        var total = api.column( this.index() ).data().reduce(function (a, b) {
          return intVal(a) + intVal(b);
        }, 0);
        // 현 페이지 합계
        var pageTotal = api.column( this.index(), { page: 'current' } ).data().reduce(function (a, b) {
          return intVal(a) + intVal(b);
        }, 0);
        // 전체 페이지 합계
        var sheetTotal = api.column( this.index(), { search: 'applied' } ).data().reduce( function (a, b) {
          return intVal(a) + intVal(b);
        }, 0 );
        // 하단에 합계 출력
        $( this.footer() ).find('span').html( parseFloat(parseFloat(pageTotal).toFixed(2)).toLocaleString()  );
        //console.log(JSON.stringify( data ));
      });
    },
    drawCallback: function(settings) {
      var api = this.api();
      var rows = api.rows({
        page: 'current'
      }).nodes();
    }
  });

  new $.fn.dataTable.FixedHeader( dtable ); // 반응형
  dtable.buttons().container().appendTo('.dt-btn');

  $('#테이블').on('click', '.iCODE, .iNAME', function (e) {
    e.preventDefault();
    var tr = $(this).closest('tr');
    var row = dtable.row( tr );
    var url = 'programs/'+row.data().id; // row: id - 이동주소 지정
    var nodeStr = e.target.nodeName;
    // 반응형인경우 자식 row 처리 구문
    var iData = window.getComputedStyle(this,':before').getPropertyValue('content');
    if(typeof iData !== 'undefined' && iData!=='none' && nodeStr == 'TD') return true;
    else window.location.href = url;
  });

  // 테이블 상단 검색과 필터링
  $('#frmProg input[name="search"]').keypress(function (e) {
    if (e.which == 13) {
      $('#frmProg input[name="page"]').val(1);
      $("#frmProg").submit();
    }
  });

  $('#frmProg').on('click', 'button.dropdown-item', function(e) {
    e.preventDefault();
    var ele=$(this);
    var optName = $(this).data("filter");
    var optValue = $(this).text();
    ele.toggleClass('dropdown-item-checked');
    if(ele.hasClass('dropdown-item-checked')) {
      $('#'+optName).val(optValue);
      $('#frmProg input[name="program"]').val(optValue);
    }
    else {
      $('#'+optName).val('');
      $('#frmProg input[name="program"]').val('');
    }
    $('#frmProg').submit();
  });

  $( "#frmProg" ).submit(function( event ) {
    //event.preventDefault();
  });

});
</script>