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

时间:2016-04-29 07:09:17

标签: javascript jquery datatables

我正在使用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 file

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

我也试图在复选框和单选按钮的基础上进行排序。请告诉我,如何做到。

3 个答案:

答案 0 :(得分:3)

您需要使用自定义排序功能,请参阅Custom data source sortingCheckbox data source

$.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' ]]
});

答案 1 :(得分:0)

谢谢@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();
    } );
};

答案 2 :(得分:0)

$.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';
    } );
};