Kode datatable yang berguna

Bismillaahirrohmaanirrohiim…

Barangkali ada yang suka menggunakan datatable untuk menampilkan table dengan bootstrap, javascript / jquery.

Berikut ini saya tulis beberapa kode / fungsi yang sering dipakai saat menggunakan datatable.

CSS dan JS yang diperlukan:

<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

    <link rel="stylesheet" href="https://cdn.datatables.net/1.12.1/css/dataTables.bootstrap.min.css" crossorigin="anonymous" referrerpolicy="no-referrer" />
    <link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.2.3/css/buttons.bootstrap.min.css" crossorigin="anonymous" referrerpolicy="no-referrer" />

Plugin lainnya:

    <script src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.12.1/js/dataTables.bootstrap.min.js"></script>

    <script src="https://cdn.datatables.net/buttons/2.2.3/js/dataTables.buttons.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.2.3/js/buttons.bootstrap.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.2.3/js/buttons.html5.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.2.3/js/buttons.print.min.js"></script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script>

Kode untuk mengaktifkan table yang akan diformat sebagai datatable:

$(".tabledata").DataTable({
    paging: false,
    info: false,
    searching: false,
    order: [],
    dom: "Bfrtip",
    buttons: [
        {
            extend: "excel",
            exportOptions: {
                columns: [":not(.notexport)"],//kecuali th dengan class notexport
                title: 'Data export',//nama file
                messageTop: 'Teks di atas',
                messageBottom: 'Teks di bawah',
                format: {
                    body: function(data, column, row) {
                        if (typeof data === 'string' || data instanceof String) {
                            data = data.replace(/<(?!br\s*\/?)[^>]+>/g, '');//menghapus tags html kecuali br
                            data = data.replace(/<br\s*\/?>/ig, "\r\n");//mengganti br dengan \r\n
                        }
                        return data;
                    }
                }
            }
        },
        {
            extend: "pdf",
            exportOptions: {
                columns: ":not(.notexport)"
            }
        },
        {
            extend: "print",
            exportOptions: {
                columns: [":not(.notexport)"]
            }
        },
    ],
});

Inisiasi datatable dari konten yang diambil dengan ajax:

Baca Juga:   Mendeteksi event keyboard dengan javascript
    $.ajax({
        type: "POST",
        data: "act=edit&did="+did+"&ke="+ke,
        url: "url",
        success:function(data) {
            $("#id_list_data").html(data);        

            var dttbl = $("#datatable").DataTable({
                "paging": false,
                "ordering": false,
                "oSearch": { "bSmart": false, "bRegex": true } //searching valid meski dalam kurung
            });
        },
        beforeSend: function(e) {
            $("#id_list_data").html("Please wait...");
        },
        complete: function(e) {

        }, error: function(e, s, a) {
            $("#id_list_data").html(\'Gagal saat load data, <a href="javascript:;" onclick="location.reload()">klik di sini untuk mengulang kembali.\');
        }
    })

Disable auto sorting pada kolom 1

"order": [] 
//disable semua kolom
"ordering": false

Sort by nilai td

<td data-sort="37">2/1/78 (37 years old)</td>

Export kolom tertentu meskipun di hidden

$(document).ready(function() {
    $('#example').DataTable( {
        dom: 'Bfrtip',
        buttons: [
            {
                extend: 'excel',
                exportOptions: {
                    columns: [ 0, ':visible' ]
                }
            },
            {
                extend: 'pdf',
                exportOptions: {
                    columns: ':visible'
                }
            },
            {
                extend: 'print',
                exportOptions: {
                    columns: [ 0, 1, 2, 5 ]
                }
            },
            'colvis'
        ]
    } );
} );

Set atau clear form search pada datatable

$("#datatable").DataTable().search("").columns().search("").draw();
jika gagal pakai di bawah ini
$("#datatable").DataTable().search("katakunci").draw();

Mengurutkan kolom tertentu dan menonaktifkan sort pada kolom lainnya

columnDefs: [{ orderable: false, targets: [0,1,3,4,5,7,8] },{ visible: true, targets: 5, ordering:true }],
//parameter orderable dan ordering sepertinya sama karena diubah tidak ada bedanya.
//namun jika utk menonaktifkan semua kolom, pake ordering: false,
//visible digunakan utk men show hide kolom

Menambahkan toolbar dan grouping tr – membuat banyak header pada tr

    var kolomgroup = 6;//kolom yg digrouping
    var colspangroup = 9;//jumlah kolom yg tampil
    $("#datatable").DataTable({
        paging: false,
        info: false,
        columnDefs: [{ orderable: false, targets: [0,1,3,4,5,7,8] },{ visible: true, targets: kolomgroup, ordering:true }],
        order: [[kolomgroup, "asc"]],
        drawCallback: function (settings) {
            var api = this.api();
            var rows = api.rows({ page: "current" }).nodes();
            var last = null;

            api
                .column(kolomgroup, { page: "current" })
                .data()
                .each(function (group, i) {
                    if (last !== group) {
                        $(rows)
                            .eq(i)
                            .before('<tr class="group bgtrhead"><td colspan="'+colspangroup+'"><b>Tujuan: ' + group + '</b></td></tr>');

                        last = group;
                    }
                });
        },
        "dom": '<"toolbar">lfrtip'
    });
    $("div.toolbar").html('<div class="pull-left"><a href="javascript:;" onclick="cekAll()">Check All</a> | <a href="javascript:;" onclick="uncekAll()">Uncheck All</a> &nbsp; &nbsp; &nbsp;</div>');

Paging true, info false tapi ingin set jumlah baris

    paging: true,
    pageLength: 100,
    info: false,
//bisa pake length menu, jika info true dan tampil pilihan jumlah baris pada table
"lengthMenu": [10, 50, 100, 500],

Bagikan

You May Also Like

About the Author: rasupe

Leave a Reply

Your email address will not be published. Required fields are marked *