1

Firstly sorry for this long explanation for my question. but I need the solution, I have spent a couple days to find the exact solution :(

This is my previous datatable:

enter image description here

This is my current datatable:

enter image description here

Current problem:

  1. The first problem is as shown in above pictures. I just added selection rows feature on it and now the blue button doesn't work, it select the row instead. Maybe the button will work again if the selection is using checkbox so it is not clickable in each column
  2. Second, I want to add another button that has function that can send all value of selected rows as array to be proceed in the next page (html/php)

Question: how to change the selection method from the current method (as shown in 2nd picture) to checkbox selection method and passing all values of selected rows to another html/php page in json/array?

This is my current datatable script for selection:

(table.php)

<table class="table table-bordered table-striped" id="lainlain" width="100%" cellspacing="0">
  <thead>
    <tr>
      <th>ID</th>
      <th>Date Apply</th>
      <th>Name</th>
      <th>School</th>
      <th>City</th>
      <th>Status</th>
      <th>Last Updated</th>
      <th>Edit</th>
    </tr>
  </thead>
  <tfoot>
    <tr>
      <th>ID</th>
      <th>Date Apply</th>
      <th>Name</th>
      <th>School</th>
      <th>City</th>
      <th>Status</th>
      <th>Last Updated</th>
      <th>Edit</th>
    </tr>
  </tfoot>
  <tbody>
    <?php
    $filterA = "$yearX-01-01";
    $filterZ = "$yearX-12-31";

    include "connect.php";
    $select = $con->prepare("SELECT id, dateApply, school, city, name, xType, xLevel, phone, status, lastUpdated FROM t_applicants WHERE dateApply between '$filterA' AND '$filterZ'");
    $select->setFetchMode(PDO::FETCH_ASSOC);
    $select->execute();
    while($data=$select->fetch()){
    ?><tr>
    <td><?php echo $data['id']; ?></td>
    <td><?php
      echo $apply = (new DateTime($data['dateApply']))->format('Y-m-d');
    ?></td>
    <td><?php echo $data['name']; ?></td>
    <td><?php echo $data['school']; ?></td>
    <td><?php echo $data['city']; ?></td>
    <td><?php echo $data['status']; ?></td>
    <td>
      <?php
        $timestamp = strtotime($data['lastUpdated']);
        $date = date('Y-m-d H:i:s', $timestamp);
        echo $date;
      ?>
    </td>
    <td>
      <!--THE Edit Button (BLUE) -->
      <button type="button" data-a="<?php echo $data['id'];?>" data-b="<?php echo $yearX; ?>" href='#detailUpdate' class="modalDetailUpdate btn btn-primary btn-xs" data-toggle="modal" data-backdrop='static' data-keyboard='false' title='Editar usuario'><span class="glyphicon glyphicon-edit"></span></button>
    </td>
    <?php
    }?>
    </tr>
  </tbody>
</table>

(datatableSchool.js)

 $(document).ready(function() {
        var dtCbsAndEvents = {
            /**
             * Whenever the table is re-drawn, update the export button labels, and disable any buttons dependent on row selection
             *
             * @events  draw.dt#orders-table, page.dt#orders-table, order.dt#orders-table, draw.dt#orders-table,
             *          column-visibility.dt#orders-table, search#orders-table, init.dt#orders-table, deselect.dt#orders-table,
             *          select.dt#orders-table
             * @param   {object}                e           jQuery event object
             * @param   {DataTables.Settings}   settings    DataTables settings object
             */
            updateOperationButtons: function(e, settings) { //page, order, draw, column-visibility search init.dt deselect.dt select.dt
                // I find that setting this to run after a 1 millisecond timeout to work for the dt.init event, otherwise, it doesnt seem to work...
                setTimeout(function() {
                    // Create an API object of the associated table
                    var dtApi = new $.fn.dataTable.Api(settings),
                        // Get the count of ALL rows on the page
                        rowCountAll = dtApi.rows().count(),
                        // Get the count of the rows on the CURRENT page
                        rowCountPage = dtApi.rows({
                            page: 'current',
                            search: 'applied'
                        }).count(),
                        // Get the count of the selected rows
                        rowCountSelected = dtApi.rows({
                            selected: true,
                            search: 'applied'
                        }).count(),
                        // DataTable button collections (labels get updated to specific values based on the class name)
                        dtBtns = {
                            // Buttons that require selected rows to be enabled
                            requireSelected: dtApi.buttons('.require-selected'),
                            // Buttons that need to show the count of ALL rows
                            addCountAll: dtApi.buttons('.show-count-all'),
                            // Buttons that need to show the count of SELECTED rows
                            addCountSelected: dtApi.buttons('.show-count-selected'),
                            // Buttons that need to show the count of rows on CURRENT PAGE
                            addCountPage: dtApi.buttons('.show-count-page'),
                            // Buttons that need to show the count of SELECTED rows, or ALL if none are selected
                            allOrSelected: dtApi.buttons('.show-all-or-selected')
                        },
                        /**
                         * If the number provided is in the thousands, this will just add a comma where its needed
                         *
                         * @param   {number|string}     num     Number (eg: 1234567)
                         * @returns {string}  Proper thousands result (eg: 12,34,567)
                         */
                        toThousands = function(num) {
                            return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")
                        },
                        /**
                         * Update the label (or text) of a button, by appending a specified count of
                         * rows to the buttons 'title' attribute
                         *
                         * @param   {number}    rowCount    Count to show in button
                         * @param   {boolean}   hideZero    If this is true, and the row count is 0, then (0) wont be appended
                         * @note    The DT button MUST have the titleAttr property defined, as that is the $().prop('title') value
                         */
                        setBtnLabelCount = function(rowCount, hideIfZero) {
                            rowCount = parseInt(rowCount)
                            hideIfZero = !!hideIfZero

                            var btnPostTxt

                            if (hideIfZero === true && !rowCount)
                                btnPostTxt = ''

                            else
                                btnPostTxt = ' ' + (rowCount > 0 ? '(' + toThousands(rowCount) + ')' : '(0)')

                            return function(btn, index) {
                                dtApi
                                    .button(btn.node)
                                    .text($(btn.node).prop('title') + btnPostTxt)
                            }
                        }

                    // Buttons that need to show the selected rows, or all rows, if none are selected
                    dtBtns.allOrSelected.each(setBtnLabelCount(rowCountSelected || rowCountAll))

                    // Buttons that need to show the count of all rows
                    dtBtns.addCountAll.each(setBtnLabelCount(rowCountAll))

                    // Buttons that need to show the count of only selected rows
                    dtBtns.addCountSelected.each(setBtnLabelCount(rowCountSelected, true))

                    // Buttons that need to show the number of rows on the current page
                    dtBtns.addCountPage.each(setBtnLabelCount(rowCountPage))

                    // Buttons that should be disabled if no rows are selected
                    dtBtns.requireSelected.enable(rowCountSelected > 0)
                }, 1)
            }
        }

        var dtInstance = $('#lainlain')
            // Update the operation button values and disabled status based on what rows are visible/selected/filtered
            .on('draw.dt page.dt order.dt draw.dt column-visibility.dt search init.dt deselect.dt select.dt', dtCbsAndEvents.updateOperationButtons)
            .DataTable({
                select: {
                    style: 'multi+shift'
                },
                buttons: []
            })

        // DataTables Buttons (Export, select, column visibility, etc)
        new $.fn.dataTable.Buttons(dtInstance, {
            name: 'tools',
            dom: {
                container: {
                    tag: 'div',
                    className: 'width-full dt-buttons dt-custom-button-container'
                }
            },
            buttons: [{
                extend: 'collection',
                name: 'select',
                text: 'Export Orders',
                titleAttr: 'Export Orders',
                className: 'btn-txt-center width-24-pc show-all-or-selected',
                autoClose: true,
                buttons: [{
                    // Copy Export
                    extend: 'collection',
                    text: 'Print',
                    autoClose: true,
                    buttons: [{
                        name: 'printAll',
                        className: 'export-rows-all show-all-or-selected',
                        text: 'Print All',
                        titleAttr: 'Print All',
                        extend: 'print',
                        autoPrint: false,
                        exportOptions: {
                            columns: ':visible :not(.no-export)'
                        }
                    }, {
                        name: 'printSelected',
                        className: 'export-rows-selected require-selected show-count-selected',
                        text: 'Print Selected',
                        titleAttr: 'Print Selected',
                        extend: 'print',
                        autoPrint: false,
                        exportOptions: {
                            modifier: {
                                selected: true,
                                search: 'applied',
                                order: 'applied'
                            },
                            columns: ':visible :not(.no-export)'
                        }
                    }, {
                        name: 'printPage',
                        className: 'export-rows-page show-count-page',
                        text: 'Print Current Page',
                        titleAttr: 'Print Current Page',
                        extend: 'print',
                        autoPrint: false,
                        exportOptions: {
                            modifier: {
                                page: 'current',
                                search: 'applied',
                                order: 'applied'
                            },
                            columns: ':visible :not(.no-export)'
                        }
                    }]
                }, {
                    // Copy Export
                    extend: 'collection',
                    text: 'Copy',
                    autoClose: true,
                    buttons: [{
                        name: 'copyAll',
                        className: 'export-rows-all show-count-all',
                        text: 'Copy All',
                        titleAttr: 'Copy All',
                        extend: 'copy',
                        exportOptions: {
                            columns: ':visible :not(.no-export)'
                        },
                        init: function(e, dt, config) {
                            //console.log( 'Button %s - Namespace: %s',config.name, config.namespace )
                        }
                    }, {
                        name: 'copySelected',
                        className: 'export-rows-selected require-selected show-count-selected',
                        text: 'Copy Selected',
                        titleAttr: 'Copy Selected',
                        extend: 'copy',
                        exportOptions: {
                            modifier: {
                                selected: true,
                                search: 'applied',
                                order: 'applied'
                            },
                            columns: ':visible :not(.no-export)'
                        }
                    }, {
                        name: 'copyPage',
                        className: 'export-rows-page show-count-page',
                        text: 'Copy Current Page',
                        titleAttr: 'Copy Current Page',
                        extend: 'copy',
                        exportOptions: {
                            modifier: {
                                page: 'current',
                                search: 'applied',
                                order: 'applied'
                            },
                            columns: ':visible :not(.no-export)'
                        }
                    }]
                }, {
                    // Excel Export
                    extend: 'collection',
                    text: 'Excel',
                    autoClose: true,
                    buttons: [{
                        name: 'excelAll',
                        className: 'export-rows-all show-count-all',
                        text: 'Export All',
                        titleAttr: 'Export All',
                        extend: 'excel',
                        exportOptions: {
                            columns: ':visible :not(.no-export)'
                        }
                    }, {
                        name: 'excelSelected',
                        className: 'export-rows-selected require-selected show-count-selected',
                        text: 'Export Selected',
                        titleAttr: 'Export Selected',
                        extend: 'excel',
                        exportOptions: {
                            modifier: {
                                selected: true,
                                search: 'applied',
                                order: 'applied'
                            },
                            columns: ':visible :not(.no-export)'
                        }
                    }, {
                        name: 'excelPage',
                        className: 'export-rows-page show-count-page',
                        text: 'Export Current Page',
                        titleAttr: 'Export Current Page',
                        extend: 'excel',
                        exportOptions: {
                            modifier: {
                                page: 'current',
                                search: 'applied',
                                order: 'applied'
                            },
                            columns: ':visible :not(.no-export)'
                        }
                    }]
                }, {
                    // CSV Export
                    extend: 'collection',
                    text: 'CSV',
                    autoClose: true,
                    buttons: [{
                        name: 'csvAll',
                        className: 'export-rows-all show-count-all',
                        text: 'Export All',
                        titleAttr: 'Export All',
                        extend: 'csv',
                        exportOptions: {
                            columns: ':visible :not(.no-export)'
                        }
                    }, {
                        name: 'csvSelected',
                        className: 'export-rows-selected require-selected show-count-selected',
                        text: 'Export Selected',
                        titleAttr: 'Export Selected',
                        extend: 'csv',
                        exportOptions: {
                            modifier: {
                                selected: true,
                                search: 'applied',
                                order: 'applied'
                            },
                            columns: ':visible :not(.no-export)'
                        }
                    }, {
                        name: 'csvPage',
                        className: 'export-rows-page show-count-page',
                        text: 'Export Current Page',
                        titleAttr: 'Export Current Page',
                        extend: 'csv',
                        exportOptions: {
                            modifier: {
                                page: 'current',
                                search: 'applied',
                                order: 'applied'
                            },
                            columns: ':visible :not(.no-export)'
                        }
                    }]
                }, {
                    // PDF Export
                    extend: 'collection',
                    text: 'PDF',
                    titleAttr: 'PDF',
                    autoClose: true,
                    buttons: [{
                        name: 'pdfAll',
                        className: 'export-rows-all show-count-all',
                        text: 'Export All',
                        titleAttr: 'Export All',
                        extend: 'pdf',
                        exportOptions: {
                            columns: ':visible :not(.no-export)'
                        }
                    }, {
                        name: 'pdfSelected',
                        className: 'export-rows-selected require-selected show-count-selected',
                        text: 'Export Selected',
                        titleAttr: 'Export Selected',
                        extend: 'pdf',
                        exportOptions: {
                            modifier: {
                                selected: true,
                                search: 'applied',
                                order: 'applied'
                            },
                            columns: ':visible :not(.no-export)'
                        }
                    }, {
                        name: 'pdfPage',
                        className: 'export-rows-page show-count-page',
                        text: 'Export Current Page',
                        titleAttr: 'Export Current Page',
                        extend: 'pdf',
                        exportOptions: {
                            modifier: {
                                page: 'current',
                                search: 'applied',
                                order: 'applied'
                            },
                            columns: ':visible :not(.no-export)'
                        }
                    }]
                }]
            }, {
                name: 'colvis',
                className: 'btn-txt-center width-24-pc',
                extend: 'colvis',
                prefixButtons: ['colvisRestore'],
                columns: ':not(.colvis-skip)'
            }, {
                extend: 'collection',
                className: 'btn-txt-center',
                name: 'select',
                text: 'Order Selection',
                titleAttr: 'Order Selection',
                autoClose: true,
                buttons: [{
                    text: 'Select All',
                    action: function(e, dt, node, config) {
                        dt.rows().select()
                    }
                }, {
                    text: 'Deselect All',
                    action: function(e, dt, node, config) {
                        dt.rows().deselect()
                    }
                }, {
                    text: 'Select Filtered',
                    action: function(e, dt, node, config) {
                        dt.rows({
                            search: 'applied'
                        }).select()
                    }
                }, {
                    text: 'Select This Page',
                    action: function(e, dt, node, config) {
                        dt.rows({
                            page: 'current'
                        }).select()
                    }
                }, {
                    //api.rows({child: 'hidden'}).ids().each(function(id,idx){ $('table#orders-table > tbody > tr#'+id+' > td:first').trigger('click') })
                    text: 'Expand Visible/Selected',
                    action: function(e, dt, node, config) {
                        dt.rows({
                            child: 'hidden'
                        }).ids().each(function(id, idx) {
                            $('table#orders-table > tbody > tr#' + id + ' > td:first').trigger('click')
                        })
                    }
                }]
            }, {
                extend: 'collection',
                text: 'Perform Action',
                titleAttr: 'Perform Action',
                className: 'require-selected show-count-selected btn-txt-center width-24-pc', //export-rows-selected require-selected show-count-selected
                name: 'action',
                autoClose: true,
                buttons: [{
                    text: 'Item Summary',
                    action: function(e, dt, node, config) {
                        var selectedRows = getSelectedIds()

                        if (!selectedRows) {
                            alert('No rows selected')
                            return
                        }

                        console.log('Selected Rows: ', selectedRows.join(','))
                    }
                }, {
                    text: 'Reprocess Selected',
                    action: function(e, dt, node, config) {
                        var selectedRows = getSelectedIds()

                        if (!selectedRows) {
                            alert('No orders selected')
                            return
                        }

                        var r = confirm("Are you sure you want to reprocess " + selectedRows.length + " order(s)?");

                        if (r !== true)
                            return

                        console.debug('Reprocessing row IDs', selectedRows)
                    }
                }, {
                    text: 'Delete Selected',
                    action: function(e, dt, node, config) {
                        var selectedRows = getSelectedIds()

                        if (!selectedRows) {
                            alert('No orders selected')
                            return
                        }

                        var conf = confirm("Are you sure you want to delete " + selectedRows.length + " order(s)?");

                        if (conf !== true)
                            return


                        console.debug('Deleting row IDs', selectedRows)
                    }
                }, {
                    text: 'Restore Selected',
                    action: function(e, dt, node, config) {
                        var selectedRows = getSelectedIds()

                        if (!selectedRows) {
                            alert('No orders selected')
                            return
                        }

                        var conf = confirm("Are you sure you want to restore " + selectedRows.length + " order(s)?");

                        if (conf !== true)
                            return

                        console.debug('Restoring row IDs', selectedRows)
                    }
                }, {
                    text: 'Set Notes',
                    action: function(e, dt, node, config) {
                        var selectedRows = getSelectedIds()

                        if (!selectedRows) {
                            alert('No orders selected')
                            return
                        }

                        var notes = prompt("Set notes for " + selectedRows.length + ' orders:');

                        if (!notes)
                            return


                        console.debug('Setting notes for row IDs', selectedRows)
                    }
                }]
            }]
        });

        dtInstance.buttons('tools', null).container().appendTo('#button-container');
    })
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Andri Setiawan
  • 49
  • 1
  • 10
  • whats the error in chrome console for the first problem? – Abhishek Anand Jan 22 '18 at 08:41
  • @AbhishekAnand Please check the question above. I just add the php script for displaying datatable. Thank you very much. – Andri Setiawan Jan 22 '18 at 09:09
  • Uncaught TypeError: $(.).popover is not a function at HTMLDocument.eval (eval at (code.jquery.com/jquery-1.12.4.js:349), :3:34) at j (jquery-1.11.3.min.js:2) at Object.add [as done] (jquery-1.11.3.min.js:2) at m.fn.init.m.fn.ready (jquery-1.11.3.min.js:2) at eval (eval at (code.jquery.com/jquery-1.12.4.js:349), :2:13) at eval () at jquery-1.11.3.min.js:2 at Function.globalEval (jquery-1.11.3.min.js:2) at m.fn.init.domManip (jquery-1.11.3.min.js:4) at m.fn.init.append (jquery-1.11.3.min.js:4) – Andri Setiawan Jan 22 '18 at 09:16
  • @AbhishekAnand Above are the consoles. – Andri Setiawan Jan 22 '18 at 09:21
  • 1
    Looks like you have loaded multiple instances of jquery in your html page. – Abhishek Anand Jan 22 '18 at 10:04
  • As for the second problem just wrap the table in form, add a column to add check boxes with diff id(you can probably give the same id used in the id column). make a hidden input box, and before submitting the form, use jquery to put the value of whatever array you want to send stringify it, and then reparse on the server side. – Abhishek Anand Jan 22 '18 at 10:06
  • @AbhishekAnand these are my file jquery: jquery-1.11.3.min.js, jquery.dataTables.js, jquery.slimscroll.min.js, are instances of jquery? – Andri Setiawan Jan 22 '18 at 14:46

1 Answers1

1

Use the following to turn of row selection for the last column:

selector: 'td:not(:last-child)' // no row selection on last column

Put this in your "select" option here to look like this:

    var dtInstance = $('#lainlain')
        // Update the operation button values and disabled status based on what rows are visible/selected/filtered
        .on('draw.dt page.dt order.dt draw.dt column-visibility.dt search init.dt deselect.dt select.dt', dtCbsAndEvents.updateOperationButtons)
        .DataTable({
            select: {
                style: 'multi+shift',
                selector: 'td:not(:last-child)'
            },
            buttons: []
        })
K Thorngren
  • 528
  • 4
  • 10
  • Thank you. your code is running. But, it is not solving the problem. the button still not working. – Andri Setiawan Jan 22 '18 at 14:41
  • 1
    The button not working is not necessarily a Datatables issue. Take a look at this SO thread for options to change your button code: https://stackoverflow.com/questions/2906582/how-to-create-an-html-button-that-acts-like-a-link – K Thorngren Jan 22 '18 at 20:30