Keep enabled checkboxes at top of jQuery DataTables, despite sort order

梦想的初衷 提交于 2019-12-24 03:08:06

问题


I want my jQuery DataTable to always display the group of enabled checkbox rows at the top and the disabled checkbox rows underneath. So far I can only achieve this by clicking on the first header label 'clicks'. Essentially I add the class 'greyed out' to the relevant rows and sort on it. Problem is that I can't sustain those 2 groups when I sort on the other headers. I also need the order to be kept when I use the column filters. For example, clicking on 'Longs' in the 'Product Group' dropdown filter should show the 2 enabled 'Longs' rows at the top and the 1 disabled 'Longs' row at the bottom. I'm afraid I'm confused and frankly out of my depth on next steps. Any advice much appreciated. Fiddle: https://jsfiddle.net/mxb6vp3b/

<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/select/1.2.0/js/dataTables.select.min.js"></script>
<script src="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css"></script>
<script src="https://cdn.datatables.net/select/1.2.0/css/select.dataTables.min.css"></script>


<form id="frm-example" action="/nosuchpage" method="POST">
  <table id="example" class="display select" cellspacing="0" width="100%">
    <thead>
      <tr>
        <th>Clicks</th>
        <th>Trading Code</th>
        <th>Product Group</th>
        <th>Product description</th>
      </tr>
    </thead>

    <tbody>
      <tr id="row250200">
        <td><input id="HS250200" type="checkbox" value="HS 250200" /></td>
        <td> 250200 </td>
        <td> Longs </td>
        <td> Iron Ore - unroasted </td>
      </tr>
      <tr id="row260111">
        <td><input id="HS260111" type="checkbox" value="HS 260111" /></td>
        <td> 260111 </td>
        <td> Raw Materials - Iron ore </td>
        <td> Iron Ore - fines, concentrate, lump </td>
      </tr>
      <tr id="row730490" class="TypeCarbon_Alloy">
        <td><input id="HS730490" type="checkbox" value="HS 730490" /></td>
        <td> 730490 </td>
        <td> Pipe &amp; tube - Seamless </td>
        <td> Seamless tube - other </td>
      </tr>
      <tr id="row730512" class="TypeCarbon_Alloy">
        <td><input id="HS730512" type="checkbox" value="HS 730512" /></td>
        <td> 730512 </td>
        <td> Longs </td>
        <td> Welded tube - line pipe, LW, >406.4mm </td>
      </tr>
      <tr id="row730230" class="TypeCarbon_Alloy_Stainless">
        <td><input id="HS730230" type="checkbox" value="HS 730230" /></td>
        <td> 730230 </td>
        <td> Longs </td>
        <td> Railway Materials </td>
      </tr>
      <tr id="row721921" class="TypeStainless">
        <td><input id="HS721921" type="checkbox" value="HS 721921" /></td>
        <td> 721921 </td>
        <td> Flats - HR plate </td>
        <td> HR plate - discrete or CTL, >10mm </td>
      </tr>
    </tbody>
  </table>
</form>
.grey_out {
  color: lightgrey;
}
$(function() {

    // Disable all rows
    $('#example td input').prop("disabled", true).closest('tr').addClass('grey_out');
    // Eanable relevant rows
    $("#HS260111, #HS730512, #HS730230").prop("disabled", false).closest('tr').removeClass('grey_out');


    $('#example').DataTable({
        orderCellsTop: true,
        scrollY: '50vh',
        scrollCollapse: true,
        orderCellsTop: true,

        'columnDefs': [{
            'targets': 0,
            'orderDataType': 'dom-checkbox',
            'orderable': true,
        }],

        "order": [
            [0, "asc"]
        ],
        responsive: true,

        initComplete: function() {
            this.api().columns([1, 2, 3]).every(function() {
                var column = this;
                var select = $('<select><option value="">Show all</option></select>')

                    .appendTo($(column.header()))
                    .on('change', function() {
                        var val = $.fn.dataTable.util.escapeRegex(
                            $(this).val()
                        );

                        column
                            .search(val ? '^' + val + '$' : '', true, false)
                            .draw();
                    });

                column.data().unique().sort().each(function(d, j) {
                    select.append('<option value="' + d + '">' + d + '</option>')
                });

            });
        }
    });


    // Sort for Enabled'
    $.fn.dataTable.ext.order['dom-checkbox'] = function(settings, col) {
        return this.api().column(col, {
            order: 'index'
        }).nodes().map(function(td, i) {
            return $(td).parent().is(':not(.grey_out)') ? '0' : '1';
        });
    }

});

回答1:


Look at orderFixed.

[...] the ordering specified by this option will always be applied to the table, regardless of user interaction.

Now add a hidden column to your table and use that as base for orderFixed:

var table = $('#example').DataTable({
   columnDefs: [
     { targets: 0, visible: false }
   ],
   orderFixed: [0, 'desc']
}) 

Then update the hidden column with for example 1 and 0 when its sibling checkbox is checked or unchecked :

$('#example').on('click', 'input[type="checkbox"]', function() {
   var row = table.row($(this).closest('tr'));
   table.cell({ row: row.index(), column: 0 } ).data( this.checked ? 1 : 0 )
   row.invalidate().draw()
})

"checked" rows will now always stay on top regardless of how the user sort the table.

I took the markup above and made a new demo for simplicity -> http://jsfiddle.net/6e56cu8u/



来源:https://stackoverflow.com/questions/49475554/keep-enabled-checkboxes-at-top-of-jquery-datatables-despite-sort-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!