基于单选按钮和复选框的数据表排序

Datatable sorting based on radio buttons and checkbox

本文关键字:数据表 排序 复选框 单选按钮      更新时间:2023-09-26

我使用的是JQuery数据表,需要对具有单选按钮和复选框的两列进行排序。数据表根据值进行排序,所以我无法根据复选框和单选按钮的已检查和未检查值进行排序。

hbs

<table id="team-members-data">
    <thead>
    <tr>
        <th>{{Name}}</th>
        <th>{{Age}}</th>
        <th>{{RadioButton Column}}</th>
        <th>{{Checkbox column}}</th>
    </tr>
    </thead>
</table>

js文件

var teamMembers = $('#team-members-data').DataTable({
    "processing": true,
    "order": [[ 3, 'asc' ], [ 2, 'asc' ],[ 1, 'asc' ], [ 0, 'asc' ]]
});

我正试图在复选框和单选按钮的基础上进行排序。让我知道怎么做。

您需要使用自定义排序函数,请参阅自定义数据源排序和复选框数据源。

$.fn.dataTable.ext.order['dom-checkbox'] = function  ( settings, col )
{
    return this.api().column( col, {order:'index'} ).nodes().map( function ( td, i ) {
        return $('input', td).prop('checked') ? '1' : '0';
    } );
};
$.fn.dataTable.ext.order['dom-text'] = function  ( settings, col )
{
    return this.api().column( col, {order:'index'} ).nodes().map( function ( td, i ) {
        return $('input', td).val();
    } );
};
var teamMembers = $('#team-members-data').DataTable({
   "columnDefs": [
      {
         "targets": 2,
         "orderDataType": "dom-text"
      }, {
         "targets": 3,
         "orderDataType": "dom-checkbox"
      }
   ],
   "order": [[ 3, 'asc' ], [ 2, 'asc' ],[ 1, 'asc' ], [ 0, 'asc' ]]
});

感谢@Gyrocode。你的回答很有帮助。这里是dom-radio的一个实现。

$.fn.dataTable.ext.order['dom-radio'] = function ( settings, col ) {
    return this.api().column( col, {order:'index'} ).nodes().map( function ( td, i ) {
        return $('input[type=radio]:checked', td).val();
    } );
};
$.fn.dataTable.ext.order['dom-radio'] = function ( settings, col ) {
    return this.api().column( col, {order:'index'} ).nodes().map( function ( td, i ) {
        return $('input', td)[1].checked ? '1' : '0';
    } );
};